Reputation:
I have created a custom REST Controller Exception Handler for my spring boot application ...
@ControllerAdvice(annotations = RestController.class)
public class RestControllerExceptionHandler {
@ExceptionHandler(TechnicalException.class)
public ResponseEntity handleTechnicalException(TechnicalException e) {
return new ResponseEntity<>(
new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
);
}
@ExceptionHandler(BusinessException.class)
public ResponseEntity handleBusinessException(BusinessException e) {
return new ResponseEntity<>(
new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
);
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity handleValidationException(ValidationException e) {
return new ResponseEntity<>(
new RestErrorMessageModel(e.getErrorCode(), e.getDetails()), BAD_REQUEST
);
}
}
... where I handle validation, business (exceptions that caused because of violation of business rules) and technical (database related, invalid request parameters, etc.) exceptions.
The exception classes have two parameters: errorCode (unique enum) and message (exception details).
As you can see from the example, for all cases I return BAD_REQUEST (400) status, which is not the best practice.
I would like to know the best way to handle HTTP statuses based on the exception category, for example: for validation errors returning BAD_REQUEST (400) status is "okay".
... or is there any way which lets spring-boot "decides" which status code to send?
Upvotes: 0
Views: 2203
Reputation: 16495
From java & spring side, use @ControllerAdvice and @ExceptionHandler is a best practice.
From values of error codes, there is no standard. But you could:
https://developer.paypal.com/docs/api/reference/api-responses/#http-status-codes
https://developer.paypal.com/docs/classic/api/errors/#10000-to-10099
Upvotes: 1
Reputation: 92
You can always setup HttpStatus property in Exception and in Handler just get value of status and configure it in ResponseEntity. Basically HttpStatus depends on context of executed task. Your Technical or Business Exception can return 400, 404, 409 etc. I think good solution is define HttpStatus during throwing suitable exception. If you dont want to define many Exception per HttpStatus you can use org.springframework.web.server.ResponseStatusException.
Upvotes: 0
Reputation:
Since the type of errors may vary in application and it is not possible to have common HTTP status for all these errors I solved it by creating custom mapper which maps error codes to HTTP statuses.
Since error codes are unique and each of them used for a special exception handling, I can map error codes to Http statuses.
Upvotes: 0