Spring Boot - Error Handling

Spring Boot Error Handling

Default Exception Handling

Java class that throws an exception.

1
2
3
4
5
6
7
@Controller
public class MyController {
@GetMapping("/getError")
public ResponseEntity<String> getError() {
throw new RuntimeException("Some Exception is thrown.");
}
}

Spring will check the Accept heather. If text/html is accepted, then show a Whitelabel Error Page. Otherwise, return json with error message

Whitelabel Error Page

Error message in Json format

1
2
3
4
5
6
7
{
"timestamp": "2019-08-14T03:27:59.421+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Some Exception is thrown.",
"path": "/getError"
}

To stop Spring from printing stack trace, set server.error.include-stacktrace property to application.properties file. Default is always

1
server.error.include-stacktrace=never

You can disable whitelabel page by setting server.error.whitelabel.enabled property to false.

1
server.error.whitelabel.enabled=false

ControllerAdvice

ControllerAdvice annotation is a specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.

ResponseEntityExceptionHandler defines convenient methods to handle Exception. It is often used with @ControllerAdvice class.

1
2
3
4
5
6
7
8
9
10
11
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {RuntimeException.class})
protected ResponseEntity<Object> handleRuntimException(
RuntimeException ex, WebRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("message", ex.getMessage());
return handleExceptionInternal(ex, map,
new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}

The error handler will handle RuntimeException globally for all @Controller

1
2
3
{
"message": "Some Exception is thrown."
}

Reference