Last active
November 20, 2019 18:02
-
-
Save itzg/ae402158e9952be2d45f78a6196e8f7f to your computer and use it in GitHub Desktop.
Spring MVC controller advice for handling custom exceptions
This file contains hidden or 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
| import java.util.Map; | |
| import javax.servlet.http.HttpServletRequest; | |
| import org.springframework.beans.factory.annotation.Autowired; | |
| import org.springframework.boot.web.servlet.error.ErrorAttributes; | |
| 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.bind.annotation.ResponseBody; | |
| import org.springframework.web.context.request.ServletWebRequest; | |
| @ControllerAdvice | |
| @ResponseBody | |
| public class RestExceptionHandler { | |
| private final ErrorAttributes errorAttributes; | |
| @Autowired | |
| public RestExceptionHandler(ErrorAttributes errorAttributes) { | |
| this.errorAttributes = errorAttributes; | |
| } | |
| @ExceptionHandler({NotFoundException.class}) | |
| public ResponseEntity<?> handleCustomExceptions( | |
| HttpServletRequest request) { | |
| return respondWith(request, HttpStatus.NOT_FOUND); | |
| } | |
| private ResponseEntity<?> respondWith(HttpServletRequest request, | |
| HttpStatus status) { | |
| Map<String, Object> body = getErrorAttributes(request); | |
| body.put("status", status.value()); | |
| return new ResponseEntity<>(body, status); | |
| } | |
| private Map<String, Object> getErrorAttributes(HttpServletRequest request) { | |
| final ServletWebRequest webRequest = new ServletWebRequest(request); | |
| return errorAttributes.getErrorAttributes(webRequest, false); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generalized here https://github.com/racker/salus-common/blob/7b9a9d099e224535bd4d8f33070cb373952c9ed7/src/main/java/com/rackspace/salus/common/web/AbstractRestExceptionHandler.java