The RestTemplate blog is the first of its kind in this article.

  • RestTemplate – How to use it in Spring or non-Spring environments
  • RestTemplate part 2 – Switching between multiple underlying HTTP client libraries
  • RestTemplate: RestTemplate: RestTemplate: RestTemplate: RestTemplate
  • RestTemplate 4 -POST request methods
  • RestTemplate 5 -DELETE, PUT, and other request methods
  • RestTemplate 6 – File upload and download versus large file streaming

1. Abnormal phenomenon

If the requested service times out or does not exist (the response status is not 200, but 400 or 500HTTP status code), the following exception will be raised:

/posts/1 /postss/1 /postss/1 /postss/1 A 404 exception is thrown because the service does not exist.

@Test public void testEntity() { String url = "http://jsonplaceholder.typicode.com/postss/1"; ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); / / it throws an exception / / the following two lines of code to perform less than HttpStatus statusCode = responseEntity. GetStatusCode (); System.out.println("HTTP response status: "+ statusCode); }Copy the code

After an exception is thrown, the code behind the program cannot be executed, making subsequent code execution impossible. In real business development, sometimes we want to get the final request result (HTTP request result status 400, 500) rather than a thrown exception, regardless of whether your server times out or the service doesn’t exist.

Two, source code parsing – default implementation

I’ll start with a conclusion: RestTemplate request result exceptions are customizable. Before we start working on our custom exception handling logic, it’s worth looking at the default implementation of exception handling. That is: why does the phenomenon mentioned in the previous section occur?

  • ResponseErrorHandler is the exception handler interface for the result of the RestTemplate request
    • The first method of the interface hasError is used to determine whether an HttpResponse is an exception response (via a status code)
    • The second method of the interface, handleError, is used to handle exception response results (non-200 status code segments)
  • The default implementation is DefaultResponseErrorHandler ResponseErrorHandler

So let’s look at how DefaultResponseErrorHandler to handle exception response? From the HttpResponse parsing the Http StatusCode, if a status code StatusCode is null, an abnormal UnknownHttpStatusCodeException.

If StatusCode exists, the series of StatusCode is resolved, which is the StatusCode segment (all except 200 are exception status codes). The resolution rule is StatusCode/100 round.

public enum Series { INFORMATIONAL(1), // 1xx/100 SUCCESSFUL(2), // 2xx/100 REDIRECTION(3), // 3xx/100 CLIENT_ERROR(4), // 4xx/100, SERVER_ERROR(5); // 5xx/100, server exception}Copy the code

The client and server exceptions are further handled by throwing an HttpClientErrorException. This is the reason for the exception in section 1

RestTemplate Custom exception handling

So we’re going to implement a custom exception, just implement the ResponseErrorHandler interface.

Public class MyRestErrorHandler implements ResponseErrorHandler {/** * Status * imitation DefaultResponseErrorHandler implementation can * / @ Override public Boolean hasError (ClientHttpResponse response) throws IOException { int rawStatusCode = response.getRawStatusCode(); HttpStatus statusCode = HttpStatus.resolve(rawStatusCode); return (statusCode ! = null ? statusCode.isError(): hasError(rawStatusCode)); } protected boolean hasError(int unknownStatusCode) { HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode); return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR); Override public void handleError(ClientHttpResponse Response) throws IOException {Override public void handleError(ClientHttpResponse Response) throws IOException {Override public void handleError(ClientHttpResponse Response) throws IOException Persisting exception information on interface requests}}Copy the code

MyRestErrorHandler is registered when the RestTemplate is instantiated. Reference: RestTemplate 1 – How to use it in Spring or non-Spring environments and RestTemplate 2 – Switching between Multiple underlying HTTP client Libraries

If you execute the sample code in section 1, you will not throw an exception. Instead, you get an HTTP Status 404. Based on this result, we can continue to execute the code in the program.

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series