gpt4 book ai didi

spring - @ControllerAdvice 覆盖异常 @ResponseStatus

转载 作者:行者123 更新时间:2023-12-04 17:44:52 26 4
gpt4 key购买 nike

我不知道为什么,但 @ControllerAdvice覆盖在 Exception 处定义的响应代码级别使用 @ResponseStatus注解。

异常(exception) :

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class GreetException extends RuntimeException {}

Controller :
@RestController
@RequestMapping("/")
public class GreetController {

@RequestMapping(method = RequestMethod.GET)
public String greet() {
throw new GreetException();
}
}

控制建议 :
@ControllerAdvice
public class ExceptionConfiguration {

@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(RuntimeException.class)
public void handleConflict() {}
}

当greet方法来自 GreetController被调用响应是 409 - CONFLICT。因为我专门提供了异常级别的响应代码,所以我预计这将是返回的代码(400 - BAD_REQUEST)。
当然,这是一个过于简化的例子,但我们用 RuntimeException 定义了一个 Controller 建议。定义,以便我们可以为每个未捕获的异常分配一个 id。

实现预期行为的正确方法是什么?

最佳答案

@ResponseStatus 注释异常的问题也就是说,这仅在其他地方未处理异常时触发。

请参阅来自 Spring article about exception handling in Spring MVC 的引用:

When an annotated exception is thrown from a controller method, and not handled elsewhere, it will automatically cause the appropriate HTTP response to be returned with the specified status-code.



同一篇文章描述了尽管有 ControllerAdvice 使其工作的方法。与一般处理程序。见 Paragraph about ControllerAdvice .

如果异常用 @ResponseStatus 注释,您基本上要做的是在通用处理程序中重新抛出异常。 :
@ControllerAdvice
public class ExceptionConfiguration {

@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(RuntimeException.class)
public void handleConflict(RuntimeException e) throws RuntimeException {
// Check for annotation
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
// Rethrow Exception
throw e;
}
else {
// Provide your general exception handling here
}
}
}

关于spring - @ControllerAdvice 覆盖异常 @ResponseStatus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460932/

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