Created
January 6, 2018 07:54
-
-
Save slmanju/6077c361f29562017eb4f39d6d463daf to your computer and use it in GitHub Desktop.
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
@RestControllerAdvice | |
public class ApiExceptionHandler { | |
@ExceptionHandler(value = { MethodArgumentTypeMismatchException.class }) | |
public ErrorResponse handleBadRequest(MethodArgumentNotValidException exception) { | |
BindingResult bindingResult = exception.getBindingResult(); | |
List<String> errors = bindingResult.getAllErrors() | |
.stream().map(DefaultMessageSourceResolvable::getDefaultMessage) | |
.collect(Collectors.toList()); | |
return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), exception.getMessage(), errors); | |
} | |
@ExceptionHandler(value = { HttpMessageNotReadableException.class }) | |
public ErrorResponse handleMessageNotReadable(HttpMessageNotReadableException exception) { | |
return new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Required request body is missing"); | |
} | |
@ExceptionHandler(value = { NoHandlerFoundException.class }) | |
public ErrorResponse handleNoHandler(NoHandlerFoundException exception) { | |
return new ErrorResponse(HttpStatus.NOT_FOUND.value(), exception.getMessage()); | |
} | |
@ExceptionHandler(value = { ResourceNotFoundException.class }) | |
public ErrorResponse handleResourceNotFound(ResourceNotFoundException exception) { | |
return new ErrorResponse(HttpStatus.NOT_FOUND.value(), exception.getMessage()); | |
} | |
@ExceptionHandler(value = { HttpRequestMethodNotSupportedException.class }) | |
public ErrorResponse handleMethodNotSupported(Exception exception) { | |
return new ErrorResponse(HttpStatus.METHOD_NOT_ALLOWED.value(), exception.getMessage()); | |
} | |
@ExceptionHandler(value = { Exception.class }) | |
public ErrorResponse handleInternalError(Exception exception) { | |
return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment