gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:16:21 25 4
gpt4 key购买 nike

我正在尝试使用 @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);
}
}

最佳答案

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

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

这样,您就不需要对异常进行任何类型检查。您甚至不需要定义自己的 @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;
}

(注解解析方法原贴here)

关于java - 如何为不同类型的异常设置不同的状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50740928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com