-
-
Save rooton/6b88d27c8408ad36e53f143b14d41972 to your computer and use it in GitHub Desktop.
Example of replacing Spring Boot "whitelabel" error page with custom error responses (with JSON response body)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company.project.controllers; | |
import com.company.project.model.api.ErrorJson; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.boot.autoconfigure.web.ErrorAttributes; | |
import org.springframework.boot.autoconfigure.web.ErrorController; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
import org.springframework.web.context.request.RequestAttributes; | |
import org.springframework.web.context.request.ServletRequestAttributes; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import java.util.Map; | |
/** | |
* Based on the helpful answer at http://stackoverflow.com/q/25356781/56285, | |
* with error details in response body added. | |
* | |
* @author Joni Karppinen | |
* @since 20.2.2015 | |
*/ | |
@RestController | |
public class CustomErrorController implements ErrorController { | |
private static final String PATH = "/error"; | |
@Value("${debug}") | |
private boolean debug; | |
@Autowired | |
private ErrorAttributes errorAttributes; | |
@RequestMapping(value = PATH) | |
ErrorJson error(HttpServletRequest request, HttpServletResponse response) { | |
// Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring. | |
// Here we just define response body. | |
return new ErrorJson(response.getStatus(), getErrorAttributes(request, debug)); | |
} | |
@Override | |
public String getErrorPath() { | |
return PATH; | |
} | |
private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { | |
RequestAttributes requestAttributes = new ServletRequestAttributes(request); | |
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment