Skip to content

Instantly share code, notes, and snippets.

@erdemaydin
Last active July 14, 2021 17:43
Show Gist options
  • Select an option

  • Save erdemaydin/c840a9365c81de14870cee4f5d7f87a8 to your computer and use it in GitHub Desktop.

Select an option

Save erdemaydin/c840a9365c81de14870cee4f5d7f87a8 to your computer and use it in GitHub Desktop.
@ControllerAdvice
public class TaskApiExceptionHandler {
private static Logger log = Logger.getLogger("TaskApiExceptionHandler");
@ExceptionHandler(InvalidInputException.class)
@ResponseBody ResponseEntity<TaskApiError> invalidInputException(InvalidInputException exception) {
return generateErrorResponse(TaskApiErrorType.INVALID_INPUT_ERROR, HttpStatus.BAD_REQUEST, exception);
}
@ExceptionHandler(RecordNotFoundException.class)
@ResponseBody ResponseEntity<TaskApiError> recordNotFoundException(RecordNotFoundException exception) {
return generateErrorResponse(TaskApiErrorType.RECORD_NOT_FOUND_ERROR, HttpStatus.NOT_FOUND, exception);
}
@ExceptionHandler({InvalidSessionException.class, UnauthorizedSessionException.class, ExpiredSessionException.class})
@ResponseBody ResponseEntity<TaskApiError> sessionExceptions(RuntimeException exception) {
return generateErrorResponse(TaskApiErrorType.SESSION_ERROR, HttpStatus.NOT_ACCEPTABLE, exception);
}
@ExceptionHandler(Throwable.class)
@ResponseBody ResponseEntity<TaskApiError> unhandledExceptions(Throwable exception) {
return generateErrorResponse(TaskApiErrorType.UNHANDLED_ERROR, HttpStatus.FORBIDDEN, exception);
}
private ResponseEntity<TaskApiError> generateErrorResponse(TaskApiErrorType errorType, HttpStatus httpStatus, Throwable exception) {
generateErrorLog(exception);
return new ResponseEntity<>(
new TaskApiError(errorType, exception.getMessage()),
httpStatus);
}
private void generateErrorLog(Throwable exception) {
log.error("ErrorMessage:" + exception.getMessage() + ", ErrorDesc:" + exception.getCause());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment