Skip to content

Commit 684ee60

Browse files
committed
Added example for spring boot exception handling
1 parent 22e98e0 commit 684ee60

File tree

11 files changed

+166
-3
lines changed

11 files changed

+166
-3
lines changed

spring-boot-rest/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
Module for the articles that are part of the Spring REST E-book:
22

33
1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration)
4+
2. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring)

spring-boot-rest/pom.xml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,22 @@
2020
<groupId>org.springframework.boot</groupId>
2121
<artifactId>spring-boot-starter-web</artifactId>
2222
</dependency>
23+
<dependency>
24+
<groupId>com.fasterxml.jackson.dataformat</groupId>
25+
<artifactId>jackson-dataformat-xml</artifactId>
26+
</dependency>
2327

2428
<dependency>
2529
<groupId>org.springframework.boot</groupId>
2630
<artifactId>spring-boot-starter-test</artifactId>
2731
<scope>test</scope>
2832
</dependency>
33+
<dependency>
34+
<groupId>net.sourceforge.htmlunit</groupId>
35+
<artifactId>htmlunit</artifactId>
36+
<version>${htmlunit.version}</version>
37+
<scope>test</scope>
38+
</dependency>
2939
</dependencies>
3040

3141
<build>
@@ -39,5 +49,6 @@
3949

4050
<properties>
4151
<start-class>com.baeldung.SpringBootRestApplication</start-class>
52+
<htmlunit.version>2.32</htmlunit.version>
4253
</properties>
4354
</project>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.errorhandling.boot;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.context.annotation.PropertySource;
6+
7+
@SpringBootApplication
8+
@PropertySource("errorhandling-application.properties")
9+
public class ErrorHandlingBootApplication {
10+
11+
public static void main(String[] args) {
12+
SpringApplication.run(ErrorHandlingBootApplication.class, args);
13+
}
14+
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.errorhandling.boot.configurations;
2+
3+
import java.util.Map;
4+
5+
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
6+
import org.springframework.stereotype.Component;
7+
import org.springframework.web.context.request.WebRequest;
8+
9+
@Component
10+
public class MyCustomErrorAttributes extends DefaultErrorAttributes {
11+
12+
@Override
13+
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
14+
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
15+
errorAttributes.put("locale", webRequest.getLocale()
16+
.toString());
17+
errorAttributes.remove("error");
18+
errorAttributes.put("cause", errorAttributes.get("message"));
19+
errorAttributes.remove("message");
20+
errorAttributes.put("status", String.valueOf(errorAttributes.get("status")));
21+
return errorAttributes;
22+
}
23+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.errorhandling.boot.configurations;
2+
3+
import java.util.Map;
4+
5+
import javax.servlet.http.HttpServletRequest;
6+
7+
import org.springframework.boot.autoconfigure.web.ErrorProperties;
8+
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
9+
import org.springframework.boot.web.servlet.error.ErrorAttributes;
10+
import org.springframework.http.HttpStatus;
11+
import org.springframework.http.MediaType;
12+
import org.springframework.http.ResponseEntity;
13+
import org.springframework.stereotype.Component;
14+
import org.springframework.web.bind.annotation.RequestMapping;
15+
16+
@Component
17+
public class MyErrorController extends BasicErrorController {
18+
19+
public MyErrorController(ErrorAttributes errorAttributes) {
20+
super(errorAttributes, new ErrorProperties());
21+
}
22+
23+
@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
24+
public ResponseEntity<Map<String, Object>> xmlError(HttpServletRequest request) {
25+
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.APPLICATION_XML));
26+
body.put("xmlkey", "the XML response is different!");
27+
HttpStatus status = getStatus(request);
28+
return new ResponseEntity<>(body, status);
29+
}
30+
31+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.errorhandling.boot.web;
2+
3+
import org.springframework.http.ResponseEntity;
4+
import org.springframework.web.bind.annotation.GetMapping;
5+
import org.springframework.web.bind.annotation.RestController;
6+
7+
@RestController
8+
public class FaultyRestController {
9+
10+
@GetMapping("/exception")
11+
public ResponseEntity<Void> requestWithException() {
12+
throw new NullPointerException("Error in the faulty controller!");
13+
}
14+
15+
}

spring-boot-rest/src/main/java/com/baeldung/web/SpringBootRestApplication.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung;
1+
package com.baeldung.web;
22

33
import org.springframework.boot.SpringApplication;
44
import org.springframework.boot.autoconfigure.SpringBootApplication;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
2+
#server.error.whitelabel.enabled=false
3+
#server.error.include-stacktrace=always
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.baeldung.errorhandling.boot;
2+
3+
import static io.restassured.RestAssured.given;
4+
import static org.assertj.core.api.Assertions.assertThat;
5+
import static org.hamcrest.Matchers.hasKey;
6+
import static org.hamcrest.Matchers.is;
7+
import static org.hamcrest.Matchers.isA;
8+
import static org.hamcrest.Matchers.not;
9+
10+
import org.junit.jupiter.api.Test;
11+
import org.springframework.http.HttpHeaders;
12+
import org.springframework.http.MediaType;
13+
14+
import com.gargoylesoftware.htmlunit.WebClient;
15+
import com.gargoylesoftware.htmlunit.html.HtmlPage;
16+
17+
public class ErrorHandlingLiveTest {
18+
19+
private static final String BASE_URL = "http://localhost:8080";
20+
private static final String EXCEPTION_ENDPOINT = "/exception";
21+
22+
private static final String ERROR_RESPONSE_KEY_PATH = "error";
23+
private static final String XML_RESPONSE_KEY_PATH = "xmlkey";
24+
private static final String LOCALE_RESPONSE_KEY_PATH = "locale";
25+
private static final String CAUSE_RESPONSE_KEY_PATH = "cause";
26+
private static final String RESPONSE_XML_ROOT = "Map";
27+
private static final String XML_RESPONSE_KEY_XML_PATH = RESPONSE_XML_ROOT + "." + XML_RESPONSE_KEY_PATH;
28+
private static final String LOCALE_RESPONSE_KEY_XML_PATH = RESPONSE_XML_ROOT + "." + LOCALE_RESPONSE_KEY_PATH;
29+
private static final String CAUSE_RESPONSE_KEY_XML_PATH = RESPONSE_XML_ROOT + "." + CAUSE_RESPONSE_KEY_PATH;
30+
private static final String CAUSE_RESPONSE_VALUE = "Error in the faulty controller!";
31+
private static final String XML_RESPONSE_VALUE = "the XML response is different!";
32+
33+
@Test
34+
public void whenRequestingFaultyEndpointAsJson_thenReceiveDefaultResponseWithConfiguredAttrs() {
35+
given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
36+
.get(EXCEPTION_ENDPOINT)
37+
.then()
38+
.body("$", hasKey(LOCALE_RESPONSE_KEY_PATH))
39+
.body(CAUSE_RESPONSE_KEY_PATH, is(CAUSE_RESPONSE_VALUE))
40+
.body("$", not(hasKey(ERROR_RESPONSE_KEY_PATH)))
41+
.body("$", not(hasKey(XML_RESPONSE_KEY_PATH)));
42+
}
43+
44+
@Test
45+
public void whenRequestingFaultyEndpointAsXml_thenReceiveXmlResponseWithConfiguredAttrs() {
46+
given().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE)
47+
.get(EXCEPTION_ENDPOINT)
48+
.then()
49+
.body(LOCALE_RESPONSE_KEY_XML_PATH, isA(String.class))
50+
.body(CAUSE_RESPONSE_KEY_XML_PATH, is(CAUSE_RESPONSE_VALUE))
51+
.body(RESPONSE_XML_ROOT, not(hasKey(ERROR_RESPONSE_KEY_PATH)))
52+
.body(XML_RESPONSE_KEY_XML_PATH, is(XML_RESPONSE_VALUE));
53+
}
54+
55+
@Test
56+
public void whenRequestingFaultyEndpointAsHtml_thenReceiveWhitelabelPageResponse() throws Exception {
57+
try (WebClient webClient = new WebClient()) {
58+
webClient.getOptions()
59+
.setThrowExceptionOnFailingStatusCode(false);
60+
HtmlPage page = webClient.getPage(BASE_URL + EXCEPTION_ENDPOINT);
61+
assertThat(page.getBody()
62+
.asText()).contains("Whitelabel Error Page");
63+
}
64+
}
65+
}

spring-boot-rest/src/test/java/com/baeldung/web/SpringContextIntegrationTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.spring.boot.rest;
1+
package com.baeldung.web;
22

33
import org.junit.Test;
44
import org.junit.runner.RunWith;

spring-rest-full/README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
1818
- [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics)
1919
- [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration)
2020
- [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration)
21-
- [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring)
2221
- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic)
2322

2423

0 commit comments

Comments
 (0)