aboudirawas
aboudirawas

Reputation: 360

Spring ExceptionHandler but for normal beans

I have been able to successfully use @ExceptionHandler annonated methodsorg.springframework.web.bind.annotation.ExceptionHandler in Controller Classes in my Spring projects to handle exceptions thrown by spring @RestController

Working example:

@Validated
@RestController
@RequestMapping(value = UrlsProperties.API_PATH, produces = MediaType.APPLICATION_JSON, consumes = { MediaType.APPLICATION_JSON })
@Api(value = "MyController", description = "MyController processing and forwarding controller")
public class MyController  {

    private static Logger log = LogManager.getLogger(MyController.class);

    ...

    @JsonFormat
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseMessage handleMissingParams(MissingServletRequestParameterException ex) {

        String name = ex.getParameterName();
        log.error(name + " parameter is missing");
        return new ResponseMessage(400, ex.getMessage());
    }
}

I am trying to achieve the same way of exception handling but for a normal bean, [ not a controller ]. Simply adding an @ExceptionHanlder annotated method did not seem to catch the exceptions thrown by that bean's methods.

My question is how to handle exceptions thrown by a bean by writing a method inside this bean?

Upvotes: 3

Views: 1739

Answers (1)

Kayaman
Kayaman

Reputation: 73578

@ExceptionHandler annotation is not for general exception handling. It's used in controllers to convert an exception into a proper HTTP response. It won't work for normal beans, because only controllers return a response.

If any code (doesn't need to be in a bean) throws an exception and you don't handle it, it would eventually propagate up to your controller's exception handler and it would be converted to a response. That would be poor design though, as you should handle exceptions as early as you can.

What you can do is create exceptions that are meant to be propagated to your exception handlers. Your code catches an exception, then re-throws it wrapped into your own exception (such as IllegalRequestException). The handler then returns an error code and details to the caller.

Upvotes: 2

Related Questions