Spring Webflux ErrorHandling - 带有@ExceptionHandler 或 DefaultErrorAttributes 的 @RestControllerAdvice?

标签 spring spring-boot exception error-handling spring-webflux

Spring Webflux 异常处理的首选方式是什么?

@RestControllerAdvice 来自 Spring MVC 而 DefaultErrorAttributes 来自 Spring Webflux。

但是,在 Spring Webflux 中,有人可以使用 @RestControllerAdvice。有什么优点/缺点?

@RestControllerAdvice

@RestControllerAdvice
public class ControllerAdvice
{
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Mono<Map<String, Object>> exceptions(Throwable e)
    {
        return Mono.just(Map.of("message", "bad"));
    }
}

扩展 DefaultErrorAttributes
@Component
public class ErrorAttributes extends DefaultErrorAttributes
{
    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace)
    {
        var ex = getError(request);

        var attributes = new LinkedHashMap<String, Object>();
        attributes.put("status", HttpStatus.BAD_REQUEST.value());
        attributes.put("message", "bad");

        return attributes;
    }
}

我想留在 react 世界中,所以我更倾向于 DefaultErrorAttributes(它与 Webflux 中的 DefaultErrorWebExceptionHandler 配合得很好)。但是,在@RestControllerAdvice 中,我也可以使用 Mono.just(...)。

最佳答案

它是一样的。像 WebMvc。

@RestControllerAdvice
public class ControllerAdvice {
    @ExceptionHandler(AnyException.class)
    public Mono<EntityResponse<YourModel>> example(AnyException exception) {
        return EntityResponse.fromObject(new YourModel()).status(HttpStatus.NOT_FOUND).build();
    }
}

关于Spring Webflux ErrorHandling - 带有@ExceptionHandler 或 DefaultErrorAttributes 的 @RestControllerAdvice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55289898/

相关文章:

java - spring boot - undertow https session 不会过期或停止 ssl 握手

exception - 如何在线程 “main” java.lang.NullPointerException中修复异常

C#:我能否从 CLR 的未处理异常中获取详细信息?

java - spring-boot 更新到 1.3.1 后 webapp 无法启动

java - 在 `WEB-INF/lib` 文件夹和 `src/main/resources` 文件夹中找不到 jar 文件的解决方案?

java - Spring 警告 : Request method 'HEAD' not supported

spring - spring mvc/rest development创建controller时出现以下: ModelAndView, Model, @ResponseBody, @ResponseEntity 混淆

java - Spring MVC 将 URL 一对一映射到 .HTML,而不暴露路径

java - 使用 JAXB 解码嵌套元素

c++ - 为什么 _ftscanf_s 会抛出异常而 _ftscanf 不会?