美文网首页
spring mvc/spring boot 全局异常处理

spring mvc/spring boot 全局异常处理

作者: 酷酷的小k | 来源:发表于2019-01-21 22:28 被阅读0次

    该类不需要controller继承!!!

    package com.smallk.controller.base;
    
    import com.smallk.common.Const;
    import com.smallk.utils.BusinessException;
    import com.smallk.utils.HttpUtil;
    import com.smallk.utils.JsonResult;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * 异常处理
     *
     * @author smallk
     * @date 2018/10/28 23:04
     */
    @Slf4j
    @ControllerAdvice
    public class ExceptionHandlerController {
    
        private static final String XHR = "XMLHttpRequest";
    
        /**
         * Global exception handling
         */
        @ExceptionHandler
        public String errorSkip(HttpServletRequest request, HttpServletResponse response, Exception e) {
            String xmlHttpRequest = request.getHeader("X-Requested-With");
            if (XHR.equals(xmlHttpRequest)) {
                JsonResult res = new JsonResult();
                if (e instanceof BusinessException) {
                    res.setMsg(e.getMessage());
                    res.setStatus(Const.BUSINESS_EXCEPTION);
                    HttpUtil.toJson(res, response);
                } else {
                    log.error("", e);
                    e.printStackTrace();
                    res.setMsg("Request error");
                    res.setStatus(Const.AJAX_ERROR);
                    response.setHeader("AJAX_ERROR", Const.AJAX_ERROR);
                    HttpUtil.toJson(res, response);
                }
                return null;
            }
            log.error("", e);
            e.printStackTrace();
            return "error/error";
        }
    }
    

    相关文章

      网友评论

          本文标题:spring mvc/spring boot 全局异常处理

          本文链接:https://www.haomeiwen.com/subject/djzhjqtx.html