其他分享
首页 > 其他分享> > springboot全局异常拦截器

springboot全局异常拦截器

作者:互联网

/**
 * 全局异常处理
 * @author Administrator
 *
 */
@ControllerAdvice
public class GloableExceptionController extends BaseController{
    
    /**
     * 拦截Exception类型异常
     * 所有的异常都可以用该类来接受
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
//    @OperLog(operModul="异常信息",operType="defaultExceptionHandler",operDesc="异常信息")
    public ModelAndView defaultExceptionHandler(HttpServletRequest request,Exception ex){
        ModelAndView mv = new ModelAndView();
        //获取请求路径
        mv.addObject("url",request.getRequestURL());
        //异常对象
        mv.addObject("ex",ex);
        //异常对象信息
        mv.addObject("message",ex.getMessage());
        System.err.println(mv);
        mv.setViewName("/defaultException");
        return mv;
    }
 
    /**
     * 自定义异常
     * @param request
     * @param ex
     * @return
     * BindingException mybatis中参数异常
     * NoHandlerFoundException 404异常
     */
    @ExceptionHandler(value = {NoHandlerFoundException.class,BindingException.class})
    public ModelAndView defaultExceptionHandler2(HttpServletRequest request,Exception ex){
        ModelAndView modelAndView = new ModelAndView("/404");
        //获取请求路径
        modelAndView.addObject("url",request.getRequestURL());
        //异常对象
        modelAndView.addObject("ex",ex);
        //异常对象信息
        modelAndView.addObject("message",ex.getMessage());
        return modelAndView;
    }
    
    /**
     * 权限校验异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {UnauthorizedException.class})
    @ResponseBody
    public AjaxResult unauthorizedException(HttpServletRequest request,Exception ex){
        return result(HTTP_ERROR,"暂无权限",ICON_ERROR);
    }
} 

 

标签:拦截器,springboot,request,param,mv,ex,ModelAndView,全局,异常
来源: https://www.cnblogs.com/ch94/p/16385491.html