Lithicas
Lithicas

Reputation: 4013

Catching all exceptions and returning an exception with list of messages

I'm wondering if there is any elegant way to catch all exceptions (specifically custom runtime exceptions) and return an exception containing a list of the messages.

Instead of having a String message, the big exception would then contain String[] message for example.

Scenario:

A REST request is made to the back-end with a JSON object containing a bunch of fields. I want to validate these fields on the backend and return a list of errors if any exceptions occur.

If both the name and lastname field are not acceptable input, I don't want to throw an exception on the invalid name and have the user change the name and submit again only to get an error message that the lastname is invalid too.

Hence why I want to collect all invalid input and return a list of these in the form of an exception.

Upvotes: 0

Views: 1936

Answers (2)

Alex
Alex

Reputation: 4669

With Spring Boot, you can use the following annotation to handle any kind of Exception for a class or a method :

@ExceptionHandler(YourExceptionHandler.class)

And you can create a class that let you regroup all your custom exception management like this (if you want to gather it) :

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
}

You can also implement the interface HandlerExceptionResolver to manage all Exceptions that ARE NOT handled by the Controllers (all the others runtime Exceptions)

public interface HandlerExceptionResolver {
    ModelAndView resolveException(HttpServletRequest request, 
            HttpServletResponse response, Object handler, Exception ex);
}

Everything is explained in details here : https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

EDIT: I just read that you added up scenario. Actually, for your special case, you should just parse the object, and return one exception (like bad object format, along with a 400 HTTP status code error, with a custom message containing all the fields that are invalid. I guess.

Upvotes: 0

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

Spring collects JSR-303/JSR-349 bean validation failures into a BindException:

Thrown when binding errors are considered fatal. Implements the BindingResult interface (and its super-interface Errors) to allow for the direct analysis of binding errors.

Instead of developing your own mechanism for bean validation you might want to read 3. Validation, Data Binding, and Type Conversion and follow the standards.

Upvotes: 1

Related Questions