2

I have a custom exception class defined as

public class CustomAuthenticationException extends RuntimeException{

}

From a controller method I am throwing this exception as below

    @RequestMapping(value="/tasks", method=RequestMethod.GET)
    public String loadTasks(HttpServletRequest request){

        try
        {   
            if (!isAuthenticatedRequest(request)) 
            {

                throw new CustomAuthenticationException();
            }

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        return "tasks/tasks";
    }

To catch this exception from that controller's scope, I have defined a method with @ExceptionHandler annotation as below

    @ExceptionHandler(CustomAuthenticationException.class)
    public void handleCustomException(CustomAuthenticationException ex){
        //method is not getting invoked
    }

When I initiate the GET request and expect the exception to be handled by the aformentioned method, I get only the error stack trace in the console. The exception handler method is never invoked.

But, with other defined exceptions like MethodArgumentNotValidException, the handler methods are invoked correctly. For example I got the following exception handler working:

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ErrorResponseHolder handleFieldValidationError(MethodArgumentNotValidException ex, HttpServletResponse response){
        //method got invoked. do something with the exception
    }

How can I resolve the issue with the custom exceptions ?

Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66
  • Possible duplicate of [Why is the Catch(Exception) almost always a bad Idea?](http://stackoverflow.com/questions/2416316/why-is-the-catchexception-almost-always-a-bad-idea) – Raedwald Apr 21 '16 at 08:41

1 Answers1

1

Handling of the exception is not proper, in a method loadTasks you are throwing the exception and catching the exception hence it is not propagating.

If you wanted to handle unhanded exceptions, for example generic exceptions (Exception.class) you need to write a method that should handle all these exception in common exception handling class.

@ExceptionHandler(Exception.class)
public void handleUnhandledException(Exception ex){
// handle the exception here
}

Once you are throwing the exception never ever catch the exception in same method, catch the exception where you are sending the proper response.

ingenious
  • 966
  • 10
  • 20
Dileep
  • 41
  • 4