如何使用 Spring WebFlux return 404
How to return 404 with Spring WebFlux
我有一个这样的控制器(在 Kotlin 中):
@RestController
@RequestMapping("/")
class CustomerController (private val service: CustomerService) {
@GetMapping("/{id}")
fun findById(@PathVariable id: String,
@RequestHeader(value = IF_NONE_MATCH) versionHeader: String?): Mono<HttpEntity<KundeResource>> =
return service.findById(id)
.switchIfEmpty(Mono.error(NotFoundException()))
.map {
// ETag stuff ...
ok().eTag("...").body(...)
}
}
我想知道是否有比抛出用 @ResponseStatus(code = NOT_FOUND)
注释的异常更好的方法
可以将方法的实现改为
,而不是抛出异常
fun findById(@PathVariable id: String,
@RequestHeader(value = IF_NONE_MATCH) versionHeader: String?): Mono<ResponseEntity<KundeResource>> =
return service.findById(id)
.map {
// ETag stuff ...
ok().eTag("...").body(...)
}
.defaultIfEmpty(notFound().build())
当 Spring 5 稳定时,我想使用 RouteFunction
而不是 @RestController。定义一个 HandlerFunction 来处理请求,然后声明一个 RouteFunction
将请求映射到 HandlerFunction:
public Mono<ServerResponse> get(ServerRequest req) {
return this.posts
.findById(req.pathVariable("id"))
.flatMap((post) -> ServerResponse.ok().body(Mono.just(post), Post.class))
.switchIfEmpty(ServerResponse.notFound().build());
}
检查完整的示例代码here。
Kotlin 版本,定义一个函数来处理请求,使用 RouteFunctionDSL
将传入请求映射到 HandlerFuncation:
fun get(req: ServerRequest): Mono<ServerResponse> {
return this.posts.findById(req.pathVariable("id"))
.flatMap { post -> ok().body(Mono.just(post), Post::class.java) }
.switchIfEmpty(notFound().build())
}
可以是一个表达式,如:
fun get(req: ServerRequest): Mono<ServerResponse> = this.posts.findById(req.pathVariable("id"))
.flatMap { post -> ok().body(Mono.just(post), Post::class.java) }
.switchIfEmpty(notFound().build())
查看 Kotlin DSL 的完整示例代码here。
如果您更喜欢传统控制器公开 REST API,请尝试这种方法。
首先定义一个异常,例如。 PostNotFoundException
。然后扔到controller里。
@GetMapping(value = "/{id}")
public Mono<Post> get(@PathVariable(value = "id") Long id) {
return this.posts.findById(id).switchIfEmpty(Mono.error(new PostNotFoundException(id)));
}
定义一个ExceptionHandler
来处理异常,并注册到HttpHandler
.
@Profile("default")
@Bean
public NettyContext nettyContext(ApplicationContext context) {
HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context)
.exceptionHandler(exceptionHandler())
.build();
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
HttpServer httpServer = HttpServer.create("localhost", this.port);
return httpServer.newHandler(adapter).block();
}
@Bean
public WebExceptionHandler exceptionHandler() {
return (ServerWebExchange exchange, Throwable ex) -> {
if (ex instanceof PostNotFoundException) {
exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
return exchange.getResponse().setComplete();
}
return Mono.error(ex);
};
}
检查complete codes here. For Spring Boot users, check this sample。
更新:在最新的spring 5.2中,我发现一般@RestControllerAdvice
适用于 webflux 应用程序中的控制器。
您可以使用 ResponseStatusException,只需扩展您的例外:
public class YourLogicException extends ResponseStatusException {
public YourLogicException(String message) {
super(HttpStatus.NOT_FOUND, message);
}
public YourLogicException(String message, Throwable cause) {
super(HttpStatus.NOT_FOUND, message, cause);
}
服役中:
public Mono<String> doLogic(Mono<YourContext> ctx) {
return ctx.map(ctx -> doSomething(ctx));
}
private String doSomething(YourContext ctx) {
try {
// some logic
} catch (Exception e) {
throw new YourLogicException("Exception message", e);
}
}
之后,您可能会收到一条漂亮的消息:
{ "timestamp": 00000000, "path": "/endpoint", "status": 404, "error": "Not found", "message": "Exception message" }
我有一个这样的控制器(在 Kotlin 中):
@RestController
@RequestMapping("/")
class CustomerController (private val service: CustomerService) {
@GetMapping("/{id}")
fun findById(@PathVariable id: String,
@RequestHeader(value = IF_NONE_MATCH) versionHeader: String?): Mono<HttpEntity<KundeResource>> =
return service.findById(id)
.switchIfEmpty(Mono.error(NotFoundException()))
.map {
// ETag stuff ...
ok().eTag("...").body(...)
}
}
我想知道是否有比抛出用 @ResponseStatus(code = NOT_FOUND)
可以将方法的实现改为
,而不是抛出异常fun findById(@PathVariable id: String,
@RequestHeader(value = IF_NONE_MATCH) versionHeader: String?): Mono<ResponseEntity<KundeResource>> =
return service.findById(id)
.map {
// ETag stuff ...
ok().eTag("...").body(...)
}
.defaultIfEmpty(notFound().build())
当 Spring 5 稳定时,我想使用 RouteFunction
而不是 @RestController。定义一个 HandlerFunction 来处理请求,然后声明一个 RouteFunction
将请求映射到 HandlerFunction:
public Mono<ServerResponse> get(ServerRequest req) {
return this.posts
.findById(req.pathVariable("id"))
.flatMap((post) -> ServerResponse.ok().body(Mono.just(post), Post.class))
.switchIfEmpty(ServerResponse.notFound().build());
}
检查完整的示例代码here。
Kotlin 版本,定义一个函数来处理请求,使用 RouteFunctionDSL
将传入请求映射到 HandlerFuncation:
fun get(req: ServerRequest): Mono<ServerResponse> {
return this.posts.findById(req.pathVariable("id"))
.flatMap { post -> ok().body(Mono.just(post), Post::class.java) }
.switchIfEmpty(notFound().build())
}
可以是一个表达式,如:
fun get(req: ServerRequest): Mono<ServerResponse> = this.posts.findById(req.pathVariable("id"))
.flatMap { post -> ok().body(Mono.just(post), Post::class.java) }
.switchIfEmpty(notFound().build())
查看 Kotlin DSL 的完整示例代码here。
如果您更喜欢传统控制器公开 REST API,请尝试这种方法。
首先定义一个异常,例如。 PostNotFoundException
。然后扔到controller里。
@GetMapping(value = "/{id}")
public Mono<Post> get(@PathVariable(value = "id") Long id) {
return this.posts.findById(id).switchIfEmpty(Mono.error(new PostNotFoundException(id)));
}
定义一个ExceptionHandler
来处理异常,并注册到HttpHandler
.
@Profile("default")
@Bean
public NettyContext nettyContext(ApplicationContext context) {
HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context)
.exceptionHandler(exceptionHandler())
.build();
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
HttpServer httpServer = HttpServer.create("localhost", this.port);
return httpServer.newHandler(adapter).block();
}
@Bean
public WebExceptionHandler exceptionHandler() {
return (ServerWebExchange exchange, Throwable ex) -> {
if (ex instanceof PostNotFoundException) {
exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
return exchange.getResponse().setComplete();
}
return Mono.error(ex);
};
}
检查complete codes here. For Spring Boot users, check this sample。
更新:在最新的spring 5.2中,我发现一般@RestControllerAdvice
适用于 webflux 应用程序中的控制器。
您可以使用 ResponseStatusException,只需扩展您的例外:
public class YourLogicException extends ResponseStatusException {
public YourLogicException(String message) {
super(HttpStatus.NOT_FOUND, message);
}
public YourLogicException(String message, Throwable cause) {
super(HttpStatus.NOT_FOUND, message, cause);
}
服役中:
public Mono<String> doLogic(Mono<YourContext> ctx) {
return ctx.map(ctx -> doSomething(ctx));
}
private String doSomething(YourContext ctx) {
try {
// some logic
} catch (Exception e) {
throw new YourLogicException("Exception message", e);
}
}
之后,您可能会收到一条漂亮的消息:
{ "timestamp": 00000000, "path": "/endpoint", "status": 404, "error": "Not found", "message": "Exception message" }