我想知道这将是解决这一一堆if
条款的更清洁的方式。作为一个aditional的信息,它是在星火框架研究项目中使用异常处理程序。
这一段代码,它的工作,它的可读性,而且可能进一步延长将其转换成一个怪物。你有什么建议,重构呢?
public ExceptionHandler<? super java.lang.Exception> handler() {
return (e, request, response) -> {
ErrorMessage error;
if (e instanceof SomeException1) {
response.status(422);
error = new ErrorMessage("message1", e.getMessage());
} else if (e instanceof SomeException2) {
response.status(404);
error = new ErrorMessage("message2", e.getMessage());
} else if (e instanceof SomeException3) {
response.status(500);
error = new ErrorMessage("message3", e.getMessage());
} else {
response.status(500);
error = new ErrorMessage("message4", e.getMessage());
}
[...]
};
}
编辑澄清:
这段代码是在应用程序的主类使用火花的exception()
方法进行注册的异常处理程序方法的一部分。事情是这样的:
public class MainClass {
public static void main(String[] args) {
//register the exception handler
exception(Exception.class, errorsHandler.handler()); //handler() is the method showed above.
}
}
避免长时间如果 - /别的链的一个好方法是使用一个映射表。你可以使用一个地图,那Exception类映射到状态代码。像这样:
private static Map<Class<?>, Integer> errorCodeMapping = new HashMap<>();
{
errorCodeMapping.put(SomeException.class, 422);
...
}
然后,您的异常处理程序将设置类似的代码
response.status(errorCodeMapping.get((e.getClass()));
这同样可以为一个异常类的错误消息映射来完成。这样,您也可以为新映射,有没有提供一个二传手被硬编码到处理程序类本身。
我的版本是这样的:
class ExceptionInfo {
Class<? extends Exception> cls;
int errCode;
String message;
public ExceptionInfo(Class<? extends Exception> cls, int errCode, String message) {
this.cls = cls;
this.errCode = errCode;
this.message = message;
}
}
// Note that the last item is Exception.class, to serve as a default.
final static List<ExceptionInfo> EXCEPTION_LIST = Arrays.asList(
new ExceptionInfo( SomeException1.class, 422, "message1"),
new ExceptionInfo( SomeException2.class, 404, "message2"),
new ExceptionInfo( SomeException3.class, 500, "message3"),
new ExceptionInfo( Exception.class, 500, "message4" )
);
ExceptionInfo searchException( Exception e ) {
return EXCEPTION_LIST.stream()
.filter( info -> info.cls.isInstance(e) )
.findFirst()
.orElseThrow( IllegalStateException::new );
}
有了这个,你可以得到给定ExceptionInfo
兼容e
,然后利用其errCode
和message
。这是instanceOf
完全兼容。当然,你可以使用,而不是直接访问这种迷你级领域的干将。