【发布时间】:2018-06-07 12:12:42
【问题描述】:
我正在尝试使用 @ControllerAdvice 处理 Spring Boot 应用程序中的异常。我不想为每种类型的异常使用单独的方法。我想只使用一种方法处理所有类型的异常,主类为@ExceptionHandler(Exception.class)
我尝试像下面这样正确处理异常,但问题是我还想为不同类型的异常设置不同类型的状态代码。
在这里,对于每种类型的异常,我都会收到 500。
谁能告诉我如何为不同类型的异常设置不同的状态码?
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleAllExceptionMethod(Exception ex,WebRequest requset) {
ExceptionMessage exceptionMessageObj = new ExceptionMessage();
exceptionMessageObj.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
exceptionMessageObj.setMessage(ex.getLocalizedMessage());
exceptionMessageObj.setError(ex.getClass().getCanonicalName());
exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());
return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(),HttpStatus.INTERNAL_SERVER_ERROR);
}
}
【问题讨论】:
-
从代码的最后一行开始。
-
您将状态码设置为
HttpStatus.INTERNAL_SERVER_ERROR,因此您将获得 500 -
我需要改变什么才能获得灵活的状态码,但有例外
标签: java spring spring-boot exception-handling