用于检查不同异常条件的大量 if/else 块的替代方案?
除了像这样的大量 if/else 块之外,是否有更优雅的方法来检查所有可能的异常类型?
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception e) {
if (e instanceof BadException)
{
displayMessage("That was bad.");
}
else if (e instanceof ReallyBadException)
{
displayMessage("That was really bad.");
}
else if (e instanceof ReallyReallyBadException)
{
displayMessage("That was really really bad.");
}
// ...
// and so on
// ...
return null;
}
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)
{
displayMessage("That was really bad.");
}
else if (e instanceof ReallyReallyBadException)
{
displayMessage("That was really really bad.");
}
// ...
// and so on
// ...
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您控制此方法中最终出现的异常,则可以利用其中嵌入的消息:
但只有当消息对最终用户有意义时才应该这样做。通常,您应该以用户不会注意到任何错误的方式处理异常。
If you control the exceptions that end up in this method, you could make use of the message embedded in them:
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.
使用多个 catch 块,请参阅此处。
Use multiple catch blocks, see here.
您可以为要显示的消息创建特定异常类型的预定义映射:
或者更好的是,您可以将映射外部化到属性文件或 ResourceBundle,以便您可以从代码以外的某个位置加载用户可见的字符串(和/或全球化)。
此代码示例无法对异常类型的层次结构使用相同的消息,但如果在映射中未找到直接类,则遍历继承链应该非常简单。
You could create a pre-defined Map of specific Exception type to the message you want to display:
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.