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 ?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.