@ControllerAdvice注解实现统一异常处理

@ControllerAdvice注解,可以对Controller中被 @RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理。

具体使用

1、定义异常处理类,可以返回json格式数据或者跳转到错误页面

返回json数据:

@ControllerAdvice
public class CustomExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception e) {
        Map map = new HashMap();
        map.put("code", 400);
        //根据异常类型返回信息
        if(e instanceof MyException){
            map.put("msg","这是自定义异常");
        }
        return map;
    }
}

或者返回页面

@ExceptionHandler(value = MyException.class)
public ModelAndView myErrorHandler(MyException e) {
    ModelAndView modelAndView = new ModelAndView();
    //指定错误页面的模板页
    modelAndView.setViewName("error");
    modelAndView.addObject("code", e.getCode());
    modelAndView.addObject("msg", e.getMsg());
    return modelAndView;
}

2、自定义异常类

//自定义异常类
@Data
public class MyException extends RuntimeException {
    private long code;
    private String msg;

    public MyException(Long code, String msg){
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public MyException(String msg){
        super(msg);
        this.msg = msg;
    }
}

项目中的具体使用,记录异常信息,浏览器相应错误信息或者跳转到错误页面:

@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常: " + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }

        //requestedWith为null,则为同步请求;requestedWith为XMLHttpRequest,则为Ajax请求
        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
        } else {
            //重定向到错误页面
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值