SpringBoot RESTful 应用中的异常处理小结 [转]
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
这里使用
@ControllerAdvice ,@ExceptionHandler(value = BaseException.class)
需要注意的是, ExceptionHandler 的优先级比 ControllerAdvice 高, 即 Controller 抛出的异常如果既可以让 ExceptionHandler 标注的方法处理, 又可以让 ControllerAdvice 标注的类中的方法处理, 则优先让 ExceptionHandler 标注的方法处理.
@RestController @ControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger("GlobalExceptionHandler"); @ExceptionHandler(value = BaseException.class) @ResponseBody public Object baseErrorHandler(HttpServletRequest req, Exception e) throws Exception { logger.error("---BaseException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage()); return "---BaseException Handler---:" + e.getMessage(); } @ExceptionHandler(value = Exception.class) @ResponseBody public Object defaultErrorHandler(HttpServletRequest req, Exception ex) throws Exception { logger.error("---DefaultException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), ex.getMessage()); JSONObject json = new JSONObject(); json.put("errorMsg", ex.getMessage()); json.put("errorCode", HttpStatus.BAD_REQUEST); return ResponseEntity.badRequest().body(json); } }
@RestController public class DemoController { private Logger logger = LoggerFactory.getLogger("GlobalExceptionHandler"); @RequestMapping("/ex1") public Object throwBaseException() throws Exception { throw new BaseException("This is BaseException."); } @RequestMapping("/ex2") public Object throwMyException1() throws Exception { throw new MyException1("This is MyException1."); } @RequestMapping("/ex3") public Object throwMyException2() throws Exception { throw new MyException2("This is MyException1."); } @RequestMapping("/ex4") public Object throwIOException() throws Exception { throw new IOException("This is IOException."); } @RequestMapping("/ex5") public Object throwNullPointerException() throws Exception { throw new NullPointerException("This is NullPointerException."); } }
相关推荐
85291545 2019-12-21
kevinweijc 2020-08-18
kikaylee 2020-08-18
寻常白昼 2020-08-15
shunelly 2020-08-09
liangzhouqu 2020-07-28
JessePinkmen 2020-07-26
xiaoxiaoniaoer 2020-07-21
Lexan 2020-06-22
heimicms 2020-06-14
tianyafengxin 2020-06-08
lynjay 2020-06-06
cenylon 2020-06-04
lqxqust 2020-06-03
宿舍 2020-05-29
Wonder的学习 2020-05-11
明天你好 2020-05-09
阿艾辣悟叩德 2020-05-06