springboot统一处理controller全局异常
背景
最近有个学弟问我如何统一处理控制器抛出的异常,我们公司虽然也做了这样的处理,但是我还没空去研究究竟是怎么实现的,怀揣着迫切的心情,就在百度上了解了一下,然后就有了这篇博客。接下来就直接简单粗暴的上干货ing~
springboot处理controller全局异常
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Result> hadleServerException(Exception exception) {
exception.printStackTrace();
//获取异常类型--我这只处理了500异常
HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
Class exceptionClazz = exception.getClass();
//可以根据不同的异常类型返回不同的值
if (Objects.equals(MissingServletRequestParameterException.class, exceptionClazz)) {
httpStatus = HttpStatus.BAD_REQUEST;
} else if (Objects.equals(HttpRequestMethodNotSupportedException.class, exceptionClazz)) {
httpStatus = HttpStatus.BAD_REQUEST;
}
//此处 ReturnResult 是自己封装的一套返回机制 eg:{"status":200,"msg":"服务器错误","data":null}
return new ResponseEntity(new ReturnResult().build(200, "服务器错误", null), httpStatus);
}
}
接下来测试类
@GetMapping("/throwExecption")
public Object throwExecption(){
int i = 1/0;
return i;
}
测试结果
看到这是不是好奇前面怎么多了一个rentHouse,这个是我自己给自己挖的坑,在该测试控制器前面添加了一个@RequestMapping("/rentHouse")。
打完收工~
愿普天程序员少粗心!