Reputation: 167
Is there any speed difference when using ControllerAdvice throwing RuntimeException, and when manually returning ResponseEntity to handle client errors?
1) ControllerAdvice
@RestController
public class ObjectController {
@PostMapping
public Object save(@RequestBody Object object) {
if (service.isInvalid(object))
throw new ObjectException("Client error");
return service.save(object);
}
}
public class ObjectException extends RuntimeException {
}
@ControllerAdvice
public class ObjectControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {ObjectException.class})
protected ResponseEntity<Object> handleConflict(ObjectException ex, WebRequest request) {
return handleExceptionInternal(ex, ex.getLocalizedMessage(), new HttpHeaders(),
HttpStatus.BAD_REQUEST, request);
}
}
2) Manually returning ResponseEntity
@RestController
public class ObjectController {
@PostMapping
public ResponseEntity<Object> save(@RequestBody Object object) {
if (service.isInvalid(object))
return new ResponseEntity<>("Client error", HttpStatus.BAD_REQUEST);
return new ResponseEntity<Object>(service.save(object), HttpStatus.OK);
}
}
Upvotes: 0
Views: 294
Reputation: 1599
No, it's not that much different. And I think using the @ControllerAdvice is a best practice when you would like to handle your Custom Exception or to centralize the Exception to a Global class. There is a simple sample in this answer: Error page registrar and Global exception handling
Hope this help.
Upvotes: 0
Reputation: 9612
I imagine the difference is response time is negligible with the second approach possibly being very slightly faster. But the real advantage of having a @ControllerAdvice class with @ExceptionHandlers is that these can be used for multiple endpoints over multiple @Controllers and you won't have to repeat the code everywhere.
Upvotes: 1