Spring Webflux错误处理-具有@ExceptionHandler或DefaultErrorAttributes的@RestControllerAdvice?

时间:2019-03-21 21:59:13

标签: 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;
    }
}

我想留在反应式世界中,所以我倾向于使用DefaultErrorAttributes(它与Webflux中的DefaultErrorWebExceptionHandler一起使用很不错)。但是,在@RestControllerAdvice中,我也可以使用Mono.just(...)。

1 个答案:

答案 0 :(得分:1)

是一样的。像 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();
    }
}
相关问题