Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ExceptionHandler doesn't handle the thrown exceptions

I have a method in my controller which will handle the exceptions thrown by the application. So I have a method like this one.

@Controller
public class ExceptionController {

    @RequestMapping(value="/error")
    @ExceptionHandler(value={Exception.class, NullPointerException.class})
    public String showError(Exception e, Model model){
        return "tiles:error";
    }
}

And to try I if it works I throw a NullPointerException in another method in other method controller:

boolean a = true;
if(a){ 
    throw new NullPointerException();
}

After the exception is thrown it is printed in the JSP, but it doesn't go throw my showError() method (I've set a breakpoint there and it never enters). showError() method will catch the exception and will show different error pages depending on the exception type (though now it always shows the same error page). If I go to the url /error it shows the error page so the showError() method is OK.

I'm using Spring 3.

What can be the problem?

Thanks.

like image 500
Javi Avatar asked May 20 '10 08:05

Javi


People also ask

How do you handle thrown exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

What will happen if a thrown exception is not handled in CPP?

Since you're not catching the exception within the context of the function, the function will terminate and the stack will be unwound as it looks for an exception handler (a catch block that would match either string, or the generic catch(...)). If it doesn't find one, your program will terminate.

What happens if a thrown exception is not caught?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.


1 Answers

If you look at your logs, you'll probably see this:

java.lang.IllegalStateException: Unsupported argument [org.springframework.ui.Model] for @ExceptionHandler method

In other words, @ExceptionHandler methods are not permitted to declare a Model parameter (see docs).

Remove that parameter (which you're not using anyway), and it should work as expected.

like image 56
skaffman Avatar answered Oct 22 '22 16:10

skaffman