有没有更好的方法来捕获带有消息的特定异常,然后执行以下操作:
try{
methodThatWillProbablyThrowASocketException();
} catch(SocketException e){
if(e.getMessage().contains("reset")){
// the connection was reset
// will ignore
} else{
throw e;
}
}
例如,如果错误状态是 404 或 502,我可以轻松比较HttpStatusException
方法getStatusCode()
,并且可以决定要做什么:
try{
methodThatWillProbablyThrowAHTTPException();
} catch(HttpStatusException e){
if(e.getStatusCode() == 404){
// not found, will not continue
}
if else(e.getStatusCode() == 502){
// server errror, try again
} else{
throw e;
}
}
大多数其他异常不给我探测方法,只是消息。
所以我的问题是,这是正确的方法吗?用字符串比较?或者,还有更好的方法?