Reputation: 71
I'm developing a REST client library and a REST server using spring/spring-boot. The library will be used as a dependency in other applications.
What is a best way to handle errors, I thought about handling the error on the server side using for example ControllerAdvice to map errors to an error DTO class. On the client side (which uses RestTemplate) I would like to:
I was trying to achieve that with ResponseErrorHandler and I came up with two solutions which don't totally satisfy me, so I would like to hear an opinion about them or get some better suggestions:
idea 1:
public List<SomeDTO> list() throws MyException {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> request = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange("endpoint/getAll", HttpMethod.GET, request, String.class);
String responseBody = response.getBody();
try {
if (MyResponseErrorHandler.isError(response.getStatusCode())) {
ErrorInfo error = objectMapper.readValue(responseBody, ErrorInfo.class);
throw new MyException();
} else {
List<SomeDTO> SomeDTOs = Arrays.asList(objectMapper.readValue(responseBody));
return SomeDTOs;
}
} catch (IOException e) {
throw new MyException();
}
}
But it looks like a lot of boilerplate for each method.
idea 2 A
throw custom exception in ResponseErrorHandler, which needs to be Runtime or IOException, but in case of IOException is wrapped with ResourceAccessException. In the client method exception could be caught and another one rethrown. But somewhere (in catch block?) the error response needs to be mapped to custom exception (what also can throw IOException)
idea 2 B don't use ResponseErrorHandler, catch HttpClientErrorException, get response body from it in the catch block using getResponseBodyAsString, map it to custom error type (catching IOException))
Any thoughts? thanks in advance
Upvotes: 3
Views: 857
Reputation: 2447
The standard way to return error in REST API is HTTP codes.
But in this case you are developing the client library so that you have option to make it your own design.
I had this situation also. Though only client library will be used by other people. So the REST API is hidden to them. Though I handled the known exceptions by ControllerAdvice and always return a object like
int code;
String message;
Object payload;
Obviously always the HTTP code is 200(OK).
The benefit of having response code as ENUM to get all the errors i have handled including specific message to create exception in client and i know the specific class of payload object as well(for successful requests). So in client side those return code (ENUM) makes it easier to throw exceptions from client side.
Upvotes: 0