springboot @ControllerAdvice统一异常处理

三层开发架构中,由于需要对Service中不同的抛出异常进行处理.往往在Controller中写很多的 try catch代码块.很不优雅

如下如此地不优雅

 @RequestMapping("userRegister")
    @ResponseBody
    public Object userRegister(String username, String verifycode, String password, String
            confirmPwd, Long recommendorId) throws Exception {
        JsonResult jsonResult = new JsonResult();
        try {
            loginInfoService.userRegister(recommendorId,username, verifycode, password, confirmPwd);
        } catch (DisplayableException e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("网络延迟...清稍后重试");
        }
        return jsonResult;
    }

下面使用统一异常处理来抽取出这一部分的代码(其实是aop增强方式)使用 @ControllerAdvice 对所有的Controller进行加强.

@ExceptionHandler指定需要处理的异常. 使用 instanceof 对不同的异常进行处理, 另外还可以根据注解根据返回 json还是html的Controller进行不同的处理

实现如下,直接上代码:

/**
 * Created by Administrator on 2018/5/3.
 * 对所有的Controller做增强
 */
@ControllerAdvice
public class WSBussinessExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(WSBussinessExceptionHandler.class);
    //指定异常类型,一般是Exception
    @ExceptionHandler(Exception.class)
    public void handler(Exception e, HandlerMethod method, HttpServletResponse resp) throws
            IOException {
        logger.error(e);
        WSResponseVO vo = new WSResponseVO(WSResponseVO.DEFAULT_FALIED_CODE,
                WSResponseVO.DEFAULT_FALIED_MSG);
        if (e instanceof WSBussinessException) {
            //如果是自定义的异常,则setmsg,其他异常的话,异常信息就是WSResponseVO.DEFAULT_FALIED_MSG
            vo.setMsg(e.getMessage());
        }
        //判断是返回json还是跳转页面(根据方法上是否贴有@ResponseBody标签)
        if (method.getMethodAnnotation(ResponseBody.class) != null) {
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(JSON.toJSONString(vo));
        } else {
            resp.sendRedirect("/error/50x.html");
        }
    }
}

配了之后Controller就不用写trycatch代码块了,清爽

    @RequestMapping("userRegister")
    @ResponseBody
    public Object userRegister(String username, String verifycode, String password, String
            confirmPwd, Long recommendorId) throws Exception {
        JsonResult jsonResult = new JsonResult();
        loginInfoService.userRegister(recommendorId, username, verifycode, password, confirmPwd);
        return jsonResult;
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值