Created
October 9, 2018 21:43
-
-
Save iamitshri/e34992a06c07ec029c8f0dd03722bf9a to your computer and use it in GitHub Desktop.
Spring Boot Exception Handler that parses Response status annotation on the Exception class
This file contains 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
package edu.wgu.dm.config; | |
import java.io.IOException; | |
import java.lang.reflect.InvocationTargetException; | |
import javax.servlet.http.HttpServletResponse; | |
import org.springframework.http.HttpStatus; | |
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.bind.annotation.ResponseStatus; | |
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; | |
import lombok.NonNull; | |
import lombok.extern.slf4j.Slf4j; | |
@ControllerAdvice | |
@Slf4j | |
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { | |
@ExceptionHandler(value = {Exception.class}) | |
@ResponseBody | |
protected void handleException(Exception ex, HttpServletResponse response) throws IOException { | |
Object statusCode = null; | |
Object reason = null; | |
ResponseStatus annotation = ex.getClass() | |
.getAnnotation(ResponseStatus.class); | |
if (annotation != null) { | |
statusCode = executeMethod(annotation, "value"); | |
reason = executeMethod(annotation, "reason"); | |
} | |
// Default setting if we don't get response code from the ResponseStatus annotation | |
if (statusCode == null) { | |
statusCode = HttpStatus.INTERNAL_SERVER_ERROR; | |
} | |
if (reason == null) { | |
reason = (ex.getMessage() != null ? ex.getMessage() : ""); | |
} | |
log.error("Exception:" + reason.toString(), ex); | |
response.sendError(Integer.parseInt(statusCode.toString()), reason.toString()); | |
} | |
private Object executeMethod(@NonNull ResponseStatus annotation, String method) { | |
Object result = null; | |
try { | |
result = annotation.annotationType() | |
.getDeclaredMethod(method) | |
.invoke(annotation, (Object[]) null); | |
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | |
| SecurityException e) { | |
log.error("Error in reading ResponseStatus annotation: ", e); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment