Spring Boot如何才能更好的捕捉异常呢?
下文笔者讲述SpringBoot中捕捉异常的方法及示例分享,如下所示
SpringBoot捕捉异常的实现思路
方式1:
使用@ControllerAdvice和@ExceptionHandler注解
实现全局异常的处理
方式2:
使用HandlerExceptionResolver接口
对全局异常的处理
例:
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 优先处理空指针异常
* @param e
* @return
*/
@ExceptionHandler(value = {NullPointerException.class})
@ResponseBody
public Object nullPointerExceptionHandler(HttpServletRequest request, NullPointerException e){
LOGGER.error("发生空指针异常,请求地址:{}, 错误信息:{}", request.getRequestURI(), e.getMessage());
return ResultMsg.fail(500, e.getMessage());
}
/**
* 兜底处理其它异常
* @param e
* @return
*/
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public Object exceptionHandler(HttpServletRequest request, Exception e){
LOGGER.error("未知异常,请求地址:{}, 错误信息:{}", request.getRequestURI(), e.getMessage());
return ResultMsg.fail(999, e.getMessage());
}
}
测试代码
@RestController
public class HelloController {
@GetMapping(value = "/add")
public String hello(){
if(1 ==1){
throw new NullPointerException("空指针测试");
}
return "hello world";
}
@GetMapping(value = "/delete")
public String delete(){
if(1 ==1){
throw new RuntimeException("其它测试");
}
return "hello world";
}
}
自定义异常类实现
自定义一个异常类CustomerException
public class CustomerException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public CustomerException(String message) {
super(message);
this.code = 500;
}
public CustomerException(Integer code, String message) {
super(message);
this.code = code;
}
}
处理自定义异常
/**
* 处理自定义的异常
* @param e
* @return
*/
@ExceptionHandler(value = {CustomerException.class})
@ResponseBody
public Object customerExceptionHandler(HttpServletRequest request, CustomerException e){
LOGGER.error("发生业务异常,请求地址:{}, 错误信息:{}", request.getRequestURI(), e.getMessage());
return ResultMsg.fail(e.getCode(), e.getMessage());
}
测试
@GetMapping(value = "/update")
public String update(){
if(1 ==1){
throw new CustomerException(4003, "请求ID不能为空");
}
return "hello world";
}
全局异常处理方式二
Spring Boot中
使用@ControllerAdvice和@ExceptionHandler注解实现全局异常处理外
还可通过HandlerExceptionResolver接口
完成全局异常的处理
@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomExceptionResolver.class);
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
LOGGER.error("接口请求出现异常,请求地址:{},错误信息:{}", request.getRequestURI(), e.getMessage());
if(e instanceof RuntimeException){
// 设置响应类型为json格式
ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
mv.addObject("code", 500);
mv.addObject("msg", e.getMessage());
return mv;
} else {
// 设置响应类型为错误页面
ModelAndView mv = new ModelAndView();
mv.addObject("message", e.getMessage());
mv.setViewName("error");
return mv;
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


