Reputation: 4587
IMHO exceptions are for exceptional cases. Exceptions should not be thrown if the scenario can be handled without exception.
Creating exception takes at least 1ms and it comes with a performance impact. So which is the best way to handle error scenario?
Scenario#1:
ResponseEntity createOrder(@RequestBody Order order){
if(order.items == null)
return ResponseEntity.badRequest().build();
...
}
Scenario#2: Spring provides @ControllerAdvice and ResponseEntityExceptionHandler as mentioned in Error Handling for REST with Spring
ResponseEntity createOrder(@RequestBody Order order){
if(order.items == null)
throw new CustomException();
...
}
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { CustomException.class })
protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
String bodyOfResponse = "Error";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
}
Upvotes: 1
Views: 408
Reputation: 939
Personally i would choose scenario #2 because it's centralized. Later you would be able to change response code for that particular exception or add some verbose logging. In terms of performance scenario #1 is obviously faster, but i would neglect that time difference
Upvotes: 1
Reputation: 1460
Well, in the particular case you have I would use Hibernate to validate and not let the invalid data into the controller to start with.
public class Order {
...
@NotNull
@NotEmpty
private List<Integer> items;
}
It will automatically create 400 error for the case items is either empty or null (internally uses exceptions though).
To handle other exceptions I would use @ExceptionHandler
as you have there, either per controller or via a @ControllerAdvice
(to catch globally).
Creating exception takes at least 1ms
Exceptions are slow, but not that slow.
Upvotes: 0