Skip to content

Instantly share code, notes, and snippets.

@fastnsilver
Created November 25, 2014 22:29
Show Gist options
  • Save fastnsilver/1490c87a0516f52f4bca to your computer and use it in GitHub Desktop.
Save fastnsilver/1490c87a0516f52f4bca to your computer and use it in GitHub Desktop.
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
@ControllerAdvice
public class ExceptionHandlerController extends BasicErrorController {
private Logger logger = LoggerFactory.getLogger(getClass());
private final ErrorAttributes errorAttributes;
@Autowired
public ExceptionHandlerController(ErrorAttributes errorAttributes) {
super(errorAttributes);
this.errorAttributes = errorAttributes;
}
// add ExceptionHandlers as needed...
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<Map<String, Object>> dataIntegrityViolationError(Throwable t, HttpServletRequest request) {
return buildResponse(t, request, HttpStatus.BAD_REQUEST);
}
protected ResponseEntity<Map<String, Object>> buildResponse(Throwable t, HttpServletRequest request, HttpStatus status) {
logger.error("Could not process request!", t);
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// only show stack trace if trace is provided as a URL query parameter
Map<String, Object> body = errorAttributes.getErrorAttributes(requestAttributes, getTraceParameter(request));
body.put("status", status.value());
body.put("error", status.getReasonPhrase());
body.put("path", request.getRequestURI());
return new ResponseEntity<Map<String, Object>>(body, status);
}
private boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment