Skip to content

Instantly share code, notes, and snippets.

@oscarnevarezleal
Created September 20, 2019 03:06
Show Gist options
  • Save oscarnevarezleal/24030102adbe5dd43d9d53727feacc45 to your computer and use it in GitHub Desktop.
Save oscarnevarezleal/24030102adbe5dd43d9d53727feacc45 to your computer and use it in GitHub Desktop.
SimpleErrorController.java for SpringBot v2.0
package com.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
@RequestMapping("/error")
public class SimpleErrorController implements ErrorController {
private final ErrorAttributes errorAttributes;
@Autowired
public SimpleErrorController(ErrorAttributes errorAttributes) {
Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
this.errorAttributes = errorAttributes;
}
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping
public Map<String, Object> error(HttpServletRequest aRequest) {
Map<String, Object> body = getErrorAttributes(aRequest, getTraceParameter(aRequest));
String trace = (String) body.get("trace");
if (trace != null) {
String[] lines = trace.split("\n\t");
body.put("trace", lines);
}
return body;
}
private boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
WebRequest webRequest = new ServletWebRequest(request);
return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment