Spring Exception message? What is it?
I think this question is generic to exceptions, but let's use my example.
I have the following straightfor开发者_如何学编程ward controller for a "user home" page after a successful login.
@Controller
@RequestMapping("/user-home")
public class UserHomeController {
private static Log log = LogFactory.getLog(UserHomeController.class);
@RequestMapping(method = RequestMethod.GET)
public String getUserHome(HttpServletRequest request) {
if (request.getSession(false) == null) {
throw new UnauthorizedClientException("Could not authenticate request. There is no session present for this request.");
} else {
return "user_home";
}
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({UnauthorizedClientException.class})
public void handle404() {
log.info("An UnauthorizedClientException was thrown inside UserHomeController.");
}
}
So, it works, i.e. I get the default 404 page when there isn't a session present, but the message I passed into the UnauthorizedClientException is nowhere to be found. The 404 page has "Message:" with nothing after it.
Where did my message go? What is normally the purpose of the message passed to the constructor of the exception?
You're misunderstanding what the UnauthorizedClientException
is for. It's not there to render a page for you, it's just there for internal control flow.
When you throw that exception, Spring catches it, and passes it to the handle404()
method. This method in turn is responsible for handling the exception accordingly.
@ExceptionHandler
-annotated methods behave just like @RequestMapping
methods in pretty much every way. That means they have to return views and models, if anything useful is to happen.
However, all your method is doing is logging the exception message to its internal logger, and returning. It doesn't return a view, and so nothing gets rendered exception the default error page; and it doesn't return a model, so no message is displayed.
You need to change your handle404()
method to (a) return the name of the JSP you want to render, and (b) add the appropriate message to the model.
How about doing something like this?
@ExceptionHandler(UnauthorizedClientException.class)
public ModelAndView handle404(UnauthorizedClientException exception) {
ModelAndView modelAndView = new ModelAndView("/errors/404");
modelAndView.addObject("message", exception.getMessage());
return modelAndView;
}
This way, you can set the message from the exception and display it in your nicely formatted 404 error page.
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({UnauthorizedClientException.class})
public void handle404() {
Does this mean that if you got a 404 and another exception class that your handler wouldn't be called? What would happen if you removed the @ExceptionHandler
annotation?
It would suggest to me that you're getting a 404 for another if your handler is invoked after this change.
精彩评论