Spring Boot Whitelabel Error Page and JSON Response

In the default state of Spring Boot, an error page called Whitelabel Error Page is displayed when 404 Not Found etc. occurs.

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Nov 18 22:16:56 JST 2019
There was an unexpected error (type=Not Found, status=404).
No message available

To see the equivalent behavior with curl, specify accept: text / html in the request header with the -H option.

$ curl -H "accept: text/html" http://localhost:8080/
<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Mon Nov 18 22:18:01 JST 2019</div><div>There was an unexpected error (type=Not Found, status=404).</div><div>No message available</div></body></html>

If the -H option is not added, JSON format data will be returned.

$ curl http://localhost:8080/
{"timestamp":"2019-11-18T13:19:03.320+0000","status":404,"error":"Not Found","message":"No message available","path":"/"}

The Spring Boot documentation states that the machine client will generate a JSON response and the browser client will generate a whitelabel error view to display in HTML format.

Spring Boot Reference Documentation

For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. For browser clients, there is a “whitelabel” error view that renders the same data in HTML format (to customize it, add a View that resolves to error).

It is the BasicErrorController class that handles error pages in Spring Boot.

In the errorHtml method of the BasicErrorController class, produces = MediaType.TEXT_HTML_VALUE is specified in the @RequestMapping annotation.

Therefore, this errorHtml method is called when the Accept header of the request contains text / html. Also, if the request does not include text / html in the Accept header, the error method is called.

The errorHtml method returns an HTML response, and the error method returns a JSON response.

The source code of the relevant part is shown below.

spring-boot/BasicErrorController.java at v2.2.1.RELEASE · spring-projects/spring-boot · GitHub

@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
  HttpStatus status = getStatus(request);
  Map<String, Object> model = Collections
      .unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
  response.setStatus(status.value());
  ModelAndView modelAndView = resolveErrorView(request, response, status, model);
  return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}

@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  HttpStatus status = getStatus(request);
  if (status == HttpStatus.NO_CONTENT) {
    return new ResponseEntity<>(status);
  }
  Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
  return new ResponseEntity<>(body, status);
}

MediaType, which is a class that indicates Content Type like text / html, is provided by Spring Framework, not Spring Boot.

spring-framework/MediaType.java at v5.2.1.RELEASE · spring-projects/spring-framework · GitHub

/**
 * A String equivalent of {@link MediaType#TEXT_HTML}.
 */
public static final String TEXT_HTML_VALUE = "text/html";

reference:

-Minimum customization of Spring Boot error page \ (Implementation of ErrorController interface ) -Qiita -Customize the display when an error such as 404 Not Found occurs in Spring Boot -Qiita

Recommended Posts

Spring Boot Whitelabel Error Page and JSON Response
Output request and response log in Spring Boot
Customize REST API error response with Spring Boot (Part 2)
Customize REST API error response with Spring Boot (Part 1)
Spring validation and error code
Minimal customization of Spring Boot error page (implementation of ErrorController interface)
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
Spring Boot + PostgreSQL error resolution method
Spring profile function, and Spring Boot application.properties
Output Spring Boot log in json format
HTTPS with Spring Boot and Let's Encrypt
Javaw.exe error when starting Spring Boot (STS)
Add spring boot and gradle to eclipse
Starting with Spring Boot 2.3, the default error page no longer contains detailed error information
About designing Spring Boot and unit test environment
Various correspondence table of Spring Framework and Spring Boot
Challenge Spring Boot
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
Create a portfolio app using Java and Spring Boot
Plans to support JDK 11 for Eclipse and Spring Boot
Testing JPA entities and repositories using Spring Boot @DataJpaTest
Spring Boot application built-in Tomcat, Apache and WebSocket integration
Try using DI container with Laravel and Spring Boot
Switch environment with Spring Boot application.properties and @Profile annotation
Spring Security usage memo: Cooperation with Spring MVC and Boot
Spring Boot with Spring Security Filter settings and addictive points
Extend Spring Boot DefaultErrorViewResolver to dynamically customize error screens
Attempt to SSR Vue.js with Spring Boot and GraalJS
Connect Spring Boot and Angular type-safely with OpenAPI Generator
Hello World comparison between Spark Framework and Spring Boot