自定义全局异常捕获
减少代码中的非必要try catch处理,增加全局异常处理,接口出现异常时可以进行捕获。
ResultBean,ResultUtil为通用controller返回结果处理,自行定义即可。
关键:@ControllerAdvice
@ControllerAdvice(basePackages = "com.example.demo.controller")
public class GlobalExceptionHandler {
private static final Log log = LogFactory.get();
//统一异常处理@ExceptionHandler,主要用于Exception
@ExceptionHandler(CustomException.class)
@ResponseBody//返回json串
public Result<?> customer(HttpServletRequest request, CustomException e) {
return ResultUtil.error(e.getCode(), e.getMsg());
}
//统一异常处理@ExceptionHandler,主要用于Exception
@ExceptionHandler(Exception.class)
@ResponseBody//返回json串
public Result<?> error(HttpServletRequest request, Exception e) {
log.error("异常信息:", e);
return ResultUtil.error("-1", "系统异常");
}
}