Alternative to massive if/else block for examining different exception conditions?
Is there a more elegant way of examining all of the possible exception types besides a massive if/else block like this?
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception e) {
if (e instanceof BadException)
{
displayMessage("That was bad.");
}
else if (e instanceof ReallyBadException)
开发者_JAVA百科 {
displayMessage("That was really bad.");
}
else if (e instanceof ReallyReallyBadException)
{
displayMessage("That was really really bad.");
}
// ...
// and so on
// ...
return null;
}
If you control the exceptions that end up in this method, you could make use of the message embedded in them:
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) {
displayMessage(e.getMessage());
return null;
}
But you should only do this, if the messages are meaningful to an enduser. Normally you should handle exceptions in a way that the user doesn't notice anything is wrong.
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception exception)
{
try
{
throw exception;
}
catch(BadException e)
{
displayMessage("That was bad.");
} catch (ReallyBadException e)
{
displayMessage("That was really bad.");
} catch (ReallyReallyBadException e)
{
displayMessage("That was really really bad.");
}
// ...
// and so on
// ...
return null;
}
Use multiple catch blocks, see here.
You could create a pre-defined Map of specific Exception type to the message you want to display:
private Map<Class<?>, String> exceptionMessages = ...;
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) {
if exceptionMessages.containsKey(e.getClass()) {
displayMessage(exceptionMessages.get(e.getClass()));
}
else {
// what to do by default?
}
return ...;
}
Or even better, you could externalize the Map to a properties file or ResourceBundle so you could load the user-visible string from some place other than code (and/or globalize it).
This code sample isn't capable of dealing with using the same message for a hierarchy of Exception types, but it should be pretty simple to walk the inheritance chain if the direct class is not found in the map.
精彩评论