Search code examples
javaspringhttpclient

Convert String error response to Http Status code


In Java+Spring application I am using, from a third party called over RestTemplate , we get the error response in the JSON with 200 response code.

e.g

{
    "errors": [{
        "reason": "did not like the request",
        "error": "BAD_REQUEST"
    }]
}

How can I convert BAD_REQUEST to the 400 integer representations. Apache HttpStatus inte does not seem to provide any interface to do so.


Solution

  • Maybe you can use org.springframework.http.HttpStatus:

    String error = "BAD_REQUEST";
    HttpStatus httpStatus = HttpStatus.valueOf(error);
    int errorIntCode = httpStatus.value();
    

    or more safe:

    String error = "BAD_REQUEST";
    HttpStatus httpStatus = Arrays.stream(HttpStatus.values())
            .filter(status -> status.name().equals(error))
            .findAny()
            .orElse(HttpStatus.INTERNAL_SERVER_ERROR);
    int errorIntCode = httpStatus.value();