Raedwald
Raedwald

Reputation: 48694

DataAccessException response status

If code called by a Spring controller throws a Spring DataAccessException, and the controller does not catch it or have an exception handler for it, will Spring return an appropriate HTTP response status to the client?

That is, do the DataAccessExceptions have suitable @ResponseStatus annotations? Or does the Spring MVC framework explicitly catch those exceptions and handle them? Or does the framework do nothing special for them, treating then like any other RuntimeException, which I guess results in an HTTP status of 500 (Internal Server Error).

Upvotes: 1

Views: 2804

Answers (1)

Shinichi Kai
Shinichi Kai

Reputation: 4523

It looks like DispatcherServlet.doService (and the subsequent methods it delegates to) just delegate an exception to the servlet container if Spring has no handler for it. Spring by default has handlers that use the @ExceptionHandler and @ResponseStatus annotations, and a promising-looking DefaultHandlerExceptionResolver. But the later does nothing with DataAccessExceptions. So, Spring MVC does nothing special for DataAccessExceptions.

If you want to map DataAccessExceptions to specific HTTP response status codes you can use an @ExceptionHandler method.

It looks like this:

@Controller
public class YourController {

  @RequestMapping(value = "foo")
  public void foo() throws DataAccessException {
    ...
  }

  @ExceptionHandler(DataAccessException.class)
  @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
  @ResponseBody
  public String handleException(DataAccessException ex) {
    return "error message";
  }
}

Upvotes: 2

Related Questions