全局异常处理

2020-12-15  本文已影响0人  指尖de旋律

习惯在controller中进行try catch 异常处理了,但其实如果不做异常处理的话,也可以采取全局异常处理的方式进行解决,同样方便统一使用、维护,具体实现如下:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

@ControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 
     * @desc 移动端接口请求参数验证异常类
     * @param e
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ModelAndView constraintViolationException(ConstraintViolationException e, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("code", MobileCode.HTTP_REQUEST_PARAMETER_CODE);
        modelAndView.addObject("msg", "传入参数格式不正确:"  + e.getMessage());
        return modelAndView;
    }
    
    @ExceptionHandler(BindException.class)
    public ModelAndView bindException(BindException e, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("code", MobileCode.HTTP_REQUEST_PARAMETER_CODE);
        modelAndView.addObject("msg", "传入参数格式不正确:"  + e.getMessage());
        return modelAndView;
    }
    
    /**
     * 
     * @desc 移动端接口请求方式不正确异常类
     * @param e
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ModelAndView httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("code", MobileCode.HTTP_REQUEST_METHOD_CODE);
        modelAndView.addObject("msg", "请求方式不正确:"  + e.getMessage());
        return modelAndView;
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读