springboot全局處理異常,並根據是否爲ajax返回不同結果

本文原文鏈接

在項目開發中,我們通常要來全局性的處理一些錯誤和異常,來給用戶定向到合適的錯誤信息,而不是輸出一大堆用戶不明白的東西

在這裏我們首先要知道springboot對錯誤和異常時分開處理的,異常需要異常處理器,錯誤需要錯誤處理器,比如404就屬於錯誤,常見的空指針就屬於異常。
springboot下,我們只需簡單的向容器中注入自己的錯誤處理器和異常處理器即可,下面直接上代碼吧:

/*此處省略導包語句
*/
@Configuration
public class ErrorAndExceptionResolverConfigure {
    @Bean
    public HandlerExceptionResolver exceptionResolver() {
	
        return new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

                response.setCharacterEncoding("utf-8");
                //ajax請求和非ajax請求區分返回
                if (isAjaxRequest(request)) {
                    try {
                        PrintWriter pw = response.getWriter();
                        pw.write("ajax req return!");
                        pw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    return new ModelAndView("/500");
                }
                return null;
            }
        };
    }


    //錯誤處理器
    @Bean
    public ErrorViewResolver errorResolver() {

        return new ErrorViewResolver() {
            @Override
            public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {

                ModelAndView mv = new ModelAndView();
                if (status.is4xxClientError()) {
                    mv.setViewName("/404");
                } else {
                    mv.setViewName("/500");
                }
                return mv;
            }
        };
    }
    private boolean isAjaxRequest(HttpServletRequest request){
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(header);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章