Java 如何处理多个路由的异常

Java 如何处理多个路由的异常,java,exception-handling,spark-java,Java,Exception Handling,Spark Java,我正在着手解决这个问题,并试图了解以统一方式处理多个路由异常的最佳方法 目前,我有许多路由所有处理以下线路的异常: ... catch (final Exception e) { ... response.status(418); return e.getMessage(); } ... 这就留下了很多需要改进的地方,主要是它们之间的异常逻辑是重复的。我知道重构可以改进它,但我想知道是否有类似于Spring中的机制,在抛出特定异常时可以执行操作,例如: @Excepti

我正在着手解决这个问题,并试图了解以统一方式处理多个路由异常的最佳方法

目前,我有许多路由所有处理以下线路的异常:

...
catch (final Exception e) {
    ...
    response.status(418);
    return e.getMessage();
}
...
这就留下了很多需要改进的地方,主要是它们之间的异常逻辑是重复的。我知道重构可以改进它,但我想知道是否有类似于Spring中的机制,在抛出特定异常时可以执行操作,例如:

@ExceptionHandler(Exception.class)
public void handleException(final Exception e, final HttpServletRequest request) {
    ...executed for the matching exception...
}

那么,是否有类似Spark的异常处理机制?我检查了文件,发现有问题。如果没有,我将继续我的重构计划。谢谢。

我一直在处理这个问题。这就是我想到的。它将需要调整到您的环境

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("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});

示例取自。

Hi@Dan我很想知道在您的环境中,您还需要哪些调整才能使其正常工作,因为我遇到了同样的问题。
get("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

exception(NotFoundException.class, (e, request, response) -> {
    response.status(404);
    response.body("Resource not found");
});