在 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/