Skip to content

Instantly share code, notes, and snippets.

@ningthoujam-lokhendro
Last active July 27, 2018 06:14
Show Gist options
  • Save ningthoujam-lokhendro/5e700af14326ff08ee9bb30c6640f344 to your computer and use it in GitHub Desktop.
Save ningthoujam-lokhendro/5e700af14326ff08ee9bb30c6640f344 to your computer and use it in GitHub Desktop.
Spring Error Controller
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
/**
* Error Controller
*/
@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){
return getErrorAttributes(aRequest, getTraceParameter(aRequest));
}
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 aRequest, boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(aRequest);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment