Skip to content

Instantly share code, notes, and snippets.

@slmanju
Created January 6, 2018 07:54
Show Gist options
  • Save slmanju/6077c361f29562017eb4f39d6d463daf to your computer and use it in GitHub Desktop.
Save slmanju/6077c361f29562017eb4f39d6d463daf to your computer and use it in GitHub Desktop.
@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