8

我有一个像这样的控制器(在 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)

4

3 回答 3

8

当 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());
}

在此处查看完整的示例代码。

Kotlin 版本,定义一个处理请求的函数,用于RouteFunctionDSL将传入的请求映射到 HandlerFunction:

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 的完整示例代码。

如果您更喜欢传统的控制器来公开 REST API,请尝试这种方法。

首先定义一个异常,例如。PostNotFoundException. 然后把它扔进控制器。

 @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);
    };
}

在此处查看完整的代码。对于 Spring Boot 用户,请查看此示例

更新:在最新的spring 5.2中,我找到了@RestControllerAdvice webflux应用中控制器的通用作品。

于 2017-08-19T08:13:50.573 回答
7

您可以使用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" }
于 2018-11-19T11:21:00.313 回答
4

方法的实现可以更改为,而不是抛出异常

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())
于 2017-08-18T14:39:04.083 回答