Dac*_*ein 6 error-handling spring exception spring-boot 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
扩展 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想留在响应式世界中,所以我更倾向于 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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7660 次 |
| 最近记录: |