spring webclient-在http错误(4xx,5xx)的情况下如何访问响应体?

w51jfk4q  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(749)

我想将我的异常从“数据库”restapi重新抛出到“后端”restapi,但我丢失了原始异常的消息。
这是我通过postman从“数据库”rest api得到的:

{
    "timestamp": "2020-03-18T15:19:14.273+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "I'm DatabaseException (0)",
    "path": "/database/api/vehicle/test/0"
}

这部分没问题。
这是我通过postman从“后端”rest api得到的:

{
    "timestamp": "2020-03-18T15:22:12.801+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "400 BAD_REQUEST \"\"; nested exception is org.springframework.web.reactive.function.client.WebClientResponseException$BadRequest: 400 Bad Request from GET http://localhost:8090/database/api/vehicle/test/0",
    "path": "/backend/api/vehicle/test/0"
}

如您所见,原来的“message”字段丢失了。
我使用:
Spring Boot2.2.5.释放
Spring启动机web
Spring启动webflux
后端和数据库从tomcat开始(web和webflux在同一个应用程序中)。
这是后端:

@GetMapping(path = "/test/{id}")
    public Mono<Integer> test(@PathVariable String id) {
        return vehicleService.test(id);
    }

使用vehicleservice.test:

public Mono<Integer> test(String id) {
        return WebClient
            .create("http://localhost:8090/database/api")
            .get()
            .uri("/vehicle/test/{id}", id)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(Integer.class);
    }

这是数据库:

@GetMapping(path = "/test/{id}")
    public Mono<Integer> test(@PathVariable String id) throws Exception {

        if (id.equals("0")) {
            throw new DatabaseException("I'm DatabaseException (0)");
        }

        return Mono.just(Integer.valueOf(2));
    }

我也试过了 return Mono.error(new DatabaseException("I'm DatabaseException (0)")); 和数据库异常:

public class DatabaseException extends ResponseStatusException {

    private static final long serialVersionUID = 1L;

    public DatabaseException(String message) {
        super(HttpStatus.BAD_REQUEST, message);

    }
}

似乎我的后端转换的React,不能找到任何答案在互联网上。

nzk0hqpo

nzk0hqpo1#

而不是 retrieveWebClient ,你可以用 exchange 它允许您处理错误并使用从服务响应检索的消息传播自定义异常。

private void execute()
{
    WebClient webClient = WebClient.create();

    webClient.get()
             .uri("http://localhost:8089")
             .exchangeToMono(this::handleResponse)
             .doOnNext(System.out::println)
             .block();  // not required, just for testing purposes
}

private Mono<Response> handleResponse(ClientResponse clientResponse)
{
    if (clientResponse.statusCode().isError())
    {
        return clientResponse.bodyToMono(Response.class)
                             .flatMap(response -> Mono.error(new RuntimeException(response.message)));
    }

    return clientResponse.bodyToMono(Response.class);
}

private static class Response
{
    private String message;

    public Response()
    {
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    @Override
    public String toString()
    {
        return "Response{" +
                "message='" + message + '\'' +
                '}';
    }
}
2ledvvac

2ledvvac2#

下面的代码现在可以工作了,这是一个不同于我最初的问题的代码,但它的想法基本相同(使用后端restapi和数据库restapi)。
我的数据库rest api:

@RestController
@RequestMapping("/user")
public class UserControl {

    @Autowired
    UserRepo userRepo;

    @Autowired
    UserMapper userMapper;

    @GetMapping("/{login}")
    public Mono<UserDTO> getUser(@PathVariable String login) throws DatabaseException {
        User user = userRepo.findByLogin(login);
        if(user == null) {
            throw new DatabaseException(HttpStatus.BAD_REQUEST, "error.user.not.found");
        }
        return Mono.just(userMapper.toDTO(user));
    }
}

userrepo只是一个@restrepritory。
usermapper使用mapstruct将实体Map到dto对象。
使用:

@Data
@EqualsAndHashCode(callSuper=false)
public class DatabaseException extends ResponseStatusException {

    private static final long serialVersionUID = 1L;

    public DatabaseException(String message) {
        super(HttpStatus.BAD_REQUEST, message);
    }
}

@data&equalsandhashcode来自lombok库。
扩展responsestatusexception在这里非常重要,如果不这样做,那么响应将被错误处理。
从数据库rest api接收数据的后端rest api:

@RestController
@RequestMapping("/user")
public class UserControl {

    @Value("${database.api.url}")
    public String databaseApiUrl;

    private String prefixedURI = "/user";

    @GetMapping("/{login}")
    public Mono<UserDTO> getUser(@PathVariable String login) {
        return WebClient
                .create(databaseApiUrl)
                .get()
                .uri(prefixedURI + "/{login}", login).retrieve()
                .onStatus(HttpStatus::isError, GlobalErrorHandler::manageError)
                .bodyToMono(UserDTO.class);
    }
}

使用globalerrorhandler::

public class GlobalErrorHandler {

    /**
     * Translation key for i18n
     */
    public final static String I18N_KEY_ERROR_TECHNICAL_EXCEPTION = "error.technical.exception";

    public static Mono<ResponseStatusException> manageError(ClientResponse clientResponse) {

        if (clientResponse.statusCode().is4xxClientError()) {
            // re-throw original status and message or they will be lost
            return clientResponse.bodyToMono(ExceptionResponseDTO.class).flatMap(response -> {
                return Mono.error(new ResponseStatusException(response.getStatus(), response.getMessage()));
            });
        } else { // Case when it's 5xx ClientError
            // User doesn't have to know which technical exception has happened
            return clientResponse.bodyToMono(ExceptionResponseDTO.class).flatMap(response -> {
                return Mono.error(new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
                        I18N_KEY_ERROR_TECHNICAL_EXCEPTION));
            });
        }

    }
}

以及ExceptionResponseTo,它是从clientresponse检索某些数据所必需的:

/**
 * Used to map <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/ClientResponse.html">ClientResponse</a> from WebFlux 
 */
@Data
@EqualsAndHashCode(callSuper=false)
public class ExceptionResponseDTO extends Exception {

    private static final long serialVersionUID = 1L;

    private HttpStatus status;

    public ExceptionResponseDTO(String message) {
        super(message);
    }

    /**
     * Status has to be converted into {@link HttpStatus}
     */
    public void setStatus(String status) {
        this.status = HttpStatus.valueOf(Integer.valueOf(status));
    }

}

另一个可能有用的相关类:exchangefilterfunctions.java
我在这个问题上发现了很多信息:
https://github.com/spring-projects/spring-framework/issues/20280
即使这些信息是旧的,它们仍然是相关的!

相关问题