Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Rest exception handling - Return generic error response

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.

like image 393
Vijay Muvva Avatar asked May 14 '15 18:05

Vijay Muvva


People also ask

How does REST API handle error response?

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.

How does spring boot handle generic exception?

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.


2 Answers

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);
    }
}
like image 156
Artur M. Avatar answered Sep 28 '22 00:09

Artur M.


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

like image 28
Sabir Khan Avatar answered Sep 28 '22 00:09

Sabir Khan