I want to know how can I handle internal server error type exceptions in Spring Data Rest such as JPA exceptions etc. due to a malformed request or a database crash. I did some research found that the better way to do this is by using @ControllerAdvice but couldn't find any working example of it. I looked at both these questions but they are still unanswered.
How can I handle exceptions with Spring Data Rest and the PagingAndSortingRepository?
global exception handling for rest exposed spring-data
Can someone help me with a working example of how to use @ControllerAdvice and write a custom error response back to client whenever there is an exception.
The simplest way we handle errors is to respond with an appropriate status code. Here are some common response codes: 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter. 401 Unauthorized – client failed to authenticate with the server.
The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown.
You can do it like this:
@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
public class GenericExceptionHandler {
@ExceptionHandler
ResponseEntity handle(Exception e) {
return new ResponseEntity("Some message", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
This is the way I do it for all request validation errors,
@RestControllerAdvice
public class ApplicationExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(MethodArgumentNotValidException exception){
StringBuilder messages = new StringBuilder();
ResponseBean response = new ResponseBean();
int count = 1;
for(ObjectError error:exception.getBindingResult().getAllErrors()){
messages.append(" "+count+"."+error.getDefaultMessage());
++count;
}
response.setMessage(messages.toString());
return response;
}
}
where ResponseBean
is my application specific class.
For JPA errors , exceptions are RuntimeExceptions and top level Exception is - org.springframework.dao.DataAccessException
.
If you wish to send a generic message to client, there is no need to catch - rethrow in your DAO, Service or Controller Layer. Just add an exception handler as above for DataAccessException
and you are done.
If you wish to set specific messages for client for specific exceptions, you need to write an application specific exception hierarchy extending DataAccessException
, lets say MyAppJPAException
. You need to catch - DataAccessException
in your application code ( either at DAO, Service or Controller layer ) and re throw MyAppJPAException
. MyAppJPAException
should have a custom message field where you should set your custom message before re throwing. In MyAppJPAException
handler, you set that message in response and can set HTTP Status as - HttpStatus.INTERNAL_SERVER_ERROR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With