Created
January 2, 2020 14:56
-
-
Save jrichardsz/408092af5daf416b3dea87a04509e3f6 to your computer and use it in GitHub Desktop.
Controller Advice - Exception Handlers
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
// from: | |
// https://niels.nu/blog/2016/controller-advice-exception-handlers.html | |
@ControllerAdvice | |
@Slf4j | |
public class ExceptionHandlers { | |
@ExceptionHandler(UserNotFoundException.class) | |
@ResponseStatus(HttpStatus.NOT_FOUND) | |
@ResponseBody | |
public ErrorResponse handleUserNotFoundException(final UserNotFoundException ex) { | |
log.error("User not found thrown", ex); | |
return new ErrorResponse("USER_NOT_FOUND", "The user was not found"); | |
} | |
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) | |
@ExceptionHandler(Throwable.class) | |
@ResponseBody | |
public ErrorResponse handleThrowable(final Throwable ex) { | |
log.error("Unexpected error", ex); | |
return new ErrorResponse("INTERNAL_SERVER_ERROR", "An unexpected internal server error occured"); | |
} | |
@Data | |
public static class ErrorResponse { | |
private final String code; | |
private final String message; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment