java 返回 404_如何使用Spring WebFlux返回404

当Spring 5稳定时,我想使用 RouteFunction 而不是@RestController . 定义HandlerFunction以处理请求,然后声明 RouteFunction 以将请求映射到HandlerFunction:

public Mono 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 {

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 = 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 . 然后把它扔进控制器 .

@GetMapping(value = "/{id}") public Mono 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 . 对于Spring Boot用户,请检查this sample .

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值