vendredi 6 mars 2015

Spring MVC ErrorController doesn't produce response

I have an ErrorController to handle all exceptions and produce a custom JSON response. But when one of my other Controllers throws a RuntimeException, the ErrorController handles the exception but doesn't produce my JSON response.


I'm using Spring MVC and Tomcat 7


web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://ift.tt/nSRXKP" xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1eWqHMP">

<!-- Other web.xml stuff-->

<error-page>
<location>/error</location>
</error-page>
</web-app>


ErrorController



@Controller
public class ErrorController {

@RequestMapping("/error")
@ResponseBody
public JsonNode handleError(HttpServletRequest request,
HttpServletResponse response, Exception e) {

int statusCode = response.getStatus();

ObjectNode error = new ObjectMapper().createObjectNode();
if (statusCode == HttpServletResponse.SC_NOT_FOUND) {
error.put("error", "Not found");
} else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
error.put("error", "Error with authentication");
} else if (statusCode == HttpServletResponse.SC_FORBIDDEN) {
error.put("error", "Insufficient permissions");
} else {
error.put("error", "Some other error occurred");
}
return error;
}
}


OtherController



@Controller
@RequestMapping("/other")
public class OtherController {

@RequestMapping(method = RequestMethod.GET)
public BufferedImage doStuff() {

// Does stuff

throw new RuntimeException();
}
}

Aucun commentaire:

Enregistrer un commentaire