如何为不同类型的异常设置不同的状态码

Spr*_*ser 2 java spring exception spring-boot

我正在尝试使用 来处理 spring boot 应用程序中的异常@ControllerAdvice。我不想为每种类型的异常使用单独的方法。我想仅使用主类的一种方法来处理所有类型的异常@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);       
        }
    }
Run Code Online (Sandbox Code Playgroud)

nic*_*ckb 5

您还可以采用不同的 Spring 方法。请注意,它不适用于本机 Java 异常(因为您需要向 Exception 类定义添加注释),您可能会也可能不会接受。

  1. 为您想要显示的状态代码定义自定义异常(或重用当前业务逻辑中的现有异常)。
  2. 添加@ResponseStatus到每个例外的顶部。
  3. 在您的控制器中,仅抛出这些异常。

这样,您不需要对异常进行任何类型检查。您甚至不需要定义自己的@ControllerAdvice. Spring 将处理显示正确的 HTTP 状态代码。如果您确实选择仍然使用@ControllerAdvice此方法来实现,则可以使用注释来获取正确的状态代码:

import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation

HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
    ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
    if (annotation != null) {
        return annotation.value();
    }
    return HttpStatus.INTERNAL_SERVER_ERROR;
}
Run Code Online (Sandbox Code Playgroud)

(注释解析方法最初发布在这里