Close

Spring MVC - Understanding Spring internal MVC Exceptions

[Last Updated: Feb 8, 2017]

Spring MVC may throw a number of exceptions internally while processing a request. These exceptions are handled by DefaultHandlerExceptionResolver. The important aspect of this resolver is, it translates the internal exception to specific HTTP status codes. It uses HttpServletResponse.sendError(statusCode) which causes the server based error page to display along with status code and error message. It doesn't have exception stacktrace.

The status codes are important specially for the automated clients (as compared to browser based human clients) which can apply their logic automatically based on the received status code in the response. Check out a list of Spring internal Exception type along with status codes here.

This exception resolver is enabled by default in DispatcherServlet.



Example

The Controller

In the first handler we are purposely setting wrong value with @PathVariable("testId") , instead of "id". It will throw MissingPathVariableException (status code 500, internal server error).

In the second handler we are throwing BindException (status code 400, bad request). We would seldom need to throw spring internal exceptions but it's just for testing.

@Controller
public class ExampleController {

    @RequestMapping("/test/{id}")
    @ResponseBody
    public String handleRequest (@PathVariable("testId") String id)
                                                        throws Exception {
        return "testId: " + id;
    }

    @RequestMapping("/test2")
    public String handleRequest () throws Exception {
        //just for testing
        throw new BindException(new Object(), "test");
    }
}

Output


/test/{id}


/test2

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.5.RELEASE: Spring Web MVC.
  • JDK 1.8
  • Maven 3.3.9

Default Handler Exception Resolver Example Select All Download
  • default-handler-exception-resolver
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleController.java

    See Also