首页 > 解决方案 > Spring Webflux:根据抛出的异常返回状态码和消息

问题描述

如何在 Spring Webflux 中确定抛出哪个异常并从中获取状态码。这是我的控制器代码的结构。

@GetMapping("/")
    fun getResults() : Mono<ResponseEntity<AccountDTO>>{
        return Service.getResult()
                .map {                     
                                       
                }.doOnError {
                    //how to get statuscode here
                    throw ResponseStatusException(HttpStatus.NOT_FOUND, it.message!!)
                }

在这里我可以得到抛出的自定义消息,但是如何获取状态码呢?而不是 HttpStatus.NOT_FOUND。我想捕获服务层抛出的状态码。或者有没有办法抛出异常?

标签: error-handlingspring-webfluxmongorepository

解决方案


I found a solution that works. 
@GetMapping("/")
    fun getResults() : Mono<ResponseEntity<AccountDTO>>{
        return Service.getResult()
                .map {                     
                                       
                }.doOnError {
                   if(it is NotFoundException)
                    {
              
                        throw ResponseStatusException(HttpStatus.NOT_FOUND)
                 
                    }
                    else{
                        throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR)
                    }
                    
                }

推荐阅读