5

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.

6
  • 1
    So your server replies with an HTTP status of 200 with that content? Commented Oct 31, 2017 at 18:52
  • Yes, its other party server response so i cannot change it. Commented Oct 31, 2017 at 18:53
  • Ask them all their possible errors, and create your own mapping to standard status codes. Commented Oct 31, 2017 at 18:53
  • @JBNizet there is no library to convert string response text to int? Commented Oct 31, 2017 at 18:55
  • 1
    How would such a library know which strings the third-party chose, and which status code they should be mapped to? These strings are not standard. Commented Oct 31, 2017 at 19:24

2 Answers 2

11

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome ! Thanks
-1

More succinct and short

HttpStatus.OK.value();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.