Skip to content

Commit 9a04bf2

Browse files
author
jacques
committed
Code update for Spring RestTemplate Exception Handling article.
1 parent d98b696 commit 9a04bf2

7 files changed

Lines changed: 168 additions & 5 deletions

File tree

‎spring-rest-simple/pom.xml‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,14 @@
3131
</dependency>
3232
<dependency>
3333
<groupId>org.springframework.boot</groupId>
34-
<artifactId>spring-boot-test</artifactId>
34+
<artifactId>spring-boot-starter-test</artifactId>
35+
<scope>test</scope>
3536
</dependency>
37+
<!--<dependency>-->
38+
<!--<groupId>org.springframework.boot</groupId>-->
39+
<!--<artifactId>spring-boot-test</artifactId>-->
40+
<!--<scope>test</scope>-->
41+
<!--</dependency>-->
3642

3743
<!-- Spring -->
3844

@@ -240,7 +246,7 @@
240246
<artifactId>cargo-maven2-plugin</artifactId>
241247
<version>${cargo-maven2-plugin.version}</version>
242248
<configuration>
243-
<wait>true</wait>
249+
<!--<wait>true</wait> caused errors on commit-->
244250
<container>
245251
<containerId>tomcat8x</containerId>
246252
<type>embedded</type>

‎spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
package org.baeldung.config;
22

3-
import java.text.SimpleDateFormat;
4-
import java.util.List;
5-
63
import org.baeldung.config.converter.KryoHttpMessageConverter;
74
import org.springframework.context.annotation.ComponentScan;
85
import org.springframework.context.annotation.Configuration;
@@ -19,6 +16,9 @@
1916
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
2017
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
2118

19+
import java.text.SimpleDateFormat;
20+
import java.util.List;
21+
2222
/*
2323
* Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml
2424
*/
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package org.baeldung.web.exception;
2+
3+
public class NotFoundException extends RuntimeException {
4+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package org.baeldung.web.handler;
2+
3+
import org.baeldung.web.exception.NotFoundException;
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
6+
import org.springframework.http.HttpStatus;
7+
import org.springframework.http.client.ClientHttpResponse;
8+
import org.springframework.stereotype.Component;
9+
import org.springframework.web.client.ResponseErrorHandler;
10+
11+
import java.io.IOException;
12+
13+
@Component
14+
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
15+
16+
private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateResponseErrorHandler.class);
17+
18+
19+
@Override
20+
public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
21+
return (httpResponse
22+
.getStatusCode()
23+
.series() == HttpStatus.Series.CLIENT_ERROR || httpResponse
24+
.getStatusCode()
25+
.series() == HttpStatus.Series.SERVER_ERROR);
26+
}
27+
28+
@Override
29+
public void handleError(ClientHttpResponse httpResponse) throws IOException {
30+
if (httpResponse
31+
.getStatusCode()
32+
.series() == HttpStatus.Series.SERVER_ERROR) {
33+
this.handleServerError(httpResponse);
34+
} else if (httpResponse
35+
.getStatusCode()
36+
.series() == HttpStatus.Series.CLIENT_ERROR) {
37+
this.handleClientError(httpResponse);
38+
}
39+
}
40+
41+
private void handleServerError(ClientHttpResponse httpResponse) {
42+
//Handle Server specific errors
43+
}
44+
45+
private void handleClientError(ClientHttpResponse httpResponse) throws IOException {
46+
//Handle Client specific errors
47+
if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
48+
//Log details here...
49+
LOGGER.info("Throwing NotFoundException...");
50+
throw new NotFoundException();
51+
}
52+
}
53+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.web.model;
2+
3+
public class Bar {
4+
private String id;
5+
private String name;
6+
7+
public String getId() {
8+
return id;
9+
}
10+
11+
public void setId(String id) {
12+
this.id = id;
13+
}
14+
15+
public String getName() {
16+
return name;
17+
}
18+
19+
public void setName(String name) {
20+
this.name = name;
21+
}
22+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package org.baeldung.web.service;
2+
3+
import org.baeldung.web.handler.RestTemplateResponseErrorHandler;
4+
import org.baeldung.web.model.Bar;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.boot.web.client.RestTemplateBuilder;
7+
import org.springframework.stereotype.Service;
8+
import org.springframework.web.client.RestTemplate;
9+
10+
11+
@Service
12+
public class BarConsumerService {
13+
14+
15+
@Autowired RestTemplateBuilder restTemplateBuilder;
16+
17+
public Bar fetchBarById(String barId) {
18+
RestTemplate restTemplate = restTemplateBuilder
19+
.errorHandler(new RestTemplateResponseErrorHandler())
20+
.build();
21+
return restTemplate.getForObject("/bars/4242", Bar.class);
22+
}
23+
24+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package org.baeldung.web.handler;
2+
3+
import org.baeldung.web.dto.Bazz;
4+
import org.baeldung.web.exception.NotFoundException;
5+
import org.baeldung.web.model.Bar;
6+
import org.junit.Assert;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
13+
import org.springframework.boot.web.client.RestTemplateBuilder;
14+
import org.springframework.http.HttpMethod;
15+
import org.springframework.http.HttpStatus;
16+
import org.springframework.test.context.ContextConfiguration;
17+
import org.springframework.test.context.junit4.SpringRunner;
18+
import org.springframework.test.web.client.ExpectedCount;
19+
import org.springframework.test.web.client.MockRestServiceServer;
20+
import org.springframework.web.client.RestTemplate;
21+
22+
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
23+
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
24+
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
25+
26+
@RunWith(SpringRunner.class)
27+
@ContextConfiguration(classes = {NotFoundException.class, Bar.class})
28+
@RestClientTest
29+
public class RestTemplateResponseErrorHandlerIntegrationTest {
30+
31+
private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateResponseErrorHandler.class);
32+
33+
@Autowired private MockRestServiceServer server;
34+
@Autowired private RestTemplateBuilder builder;
35+
36+
37+
@Test(expected = NotFoundException.class)
38+
public void givenCallToRemoteApi_when404ErrorReceived_throwNotFoundException() {
39+
Assert.assertNotNull(this.builder);
40+
Assert.assertNotNull(this.server);
41+
42+
RestTemplate restTemplate = this.builder
43+
.errorHandler(new RestTemplateResponseErrorHandler())
44+
.build();
45+
46+
this.server
47+
.expect(ExpectedCount.once(), requestTo("/bars/4242"))
48+
.andExpect(method(HttpMethod.GET))
49+
.andRespond(withStatus(HttpStatus.NOT_FOUND));
50+
51+
Bar response = restTemplate.getForObject("/bars/4242", Bar.class);
52+
this.server.verify();
53+
}
54+
}

0 commit comments

Comments
 (0)