我正在处理火花框架,并试图理解以统一的方式处理多个路由的异常的最佳方法。
目前,我有许多所有按照以下方式处理异常的路由:
...
catch (final Exception e) {
...
response.status(418);
return e.getMessage();
}
...这还需要改进很多地方,主要是异常逻辑在它们之间重复。我知道可以通过重构来改进它,但我想知道是否有类似于Spring中的ExceptionHandler机制的地方,在抛出特定异常时,您可以执行一个操作,例如:
@ExceptionHandler(Exception.class)
public void handleException(final Exception e, final HttpServletRequest request) {
...executed for the matching exception...
}那么,是否存在用于异常处理的火花式机制?我查过文件了,结果很短。如果没有,我将继续我的重构计划。谢谢。
发布于 2015-02-06 19:54:44
您可以处理这样的异常:
get("/throwexception", (request, response) -> {
throw new NotFoundException();
});
exception(NotFoundException.class, (e, request, response) -> {
response.status(404);
response.body("Resource not found");
});示例摘自火花文档。
发布于 2014-02-01 19:24:56
我一直在处理这个问题。这就是我想出来的。它将需要调整你的环境。
public class ExceptionHandler extends MustacheTemplateHandler
{
private final WrappedHandler inter;
public abstract static class WrappedHandler
{
public abstract Object handle(Request req, Response res);
}
public static ExceptionHandler wrap(String path, WrappedHandler internal)
{
return new ExceptionHandler(path, internal);
}
private ExceptionHandler(String path, WrappedHandler internal)
{
super(path);
inter = internal;
}
@Override
public Object handle(Request req, Response res)
{
try
{
return inter.handle(req, res);
}
catch (Exception e)
{
e.printStackTrace();
return new ModelAndView(e, "errors");
}
}
}然后(使用导入静态):
get(wrap("/download", new DownloadHandler()));
post(wrap("/upload", new UploadHandler()));https://stackoverflow.com/questions/13605334
复制相似问题