三层开发架构中,由于需要对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;
}