Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zeromancer/e1fa1f5e9f36885b1278fb20670310f5 to your computer and use it in GitHub Desktop.
Save zeromancer/e1fa1f5e9f36885b1278fb20670310f5 to your computer and use it in GitHub Desktop.
Custom exception handling for Spring Boot
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
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.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
public class GlobalControllerExceptionHandler {
// Painfully add fields yourselve like DefaultErrorAttributes, ResponseEntityExceptionHandler
// @ExceptionHandler(IllegalArgumentException.class)
// public ResponseEntity<Map<String, Object>> illegalArgumentExceptionToBadRequest(
// IllegalArgumentException e, WebRequest request) {
// Map<String, Object> json = new LinkedHashMap<>();
// json.put("timestamp", new Date());
// json.put("status", HttpStatus.BAD_REQUEST);
// json.put("exception", e.getClass());
// json.put("message", e.getMessage());
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(json);
// }
// Good links
// https://www.toptal.com/java/spring-boot-rest-api-error-handling
// https://gist.github.com/matsev/4519323
// Solution taken from:
// https://stackoverflow.com/questions/26236811/spring-boot-customize-http-error-response
@ExceptionHandler
void handleIllegalArgumentException(IllegalArgumentException e, HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment