Skip to content

Instantly share code, notes, and snippets.

@jrichardsz
Created January 2, 2020 14:56
Show Gist options
  • Save jrichardsz/408092af5daf416b3dea87a04509e3f6 to your computer and use it in GitHub Desktop.
Save jrichardsz/408092af5daf416b3dea87a04509e3f6 to your computer and use it in GitHub Desktop.
Controller Advice - Exception Handlers
// 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