簡體   English   中英

如何處理多個Route的異常

[英]How to handle exceptions for multiple Route

我正在掌握Spark框架,並且我正在嘗試理解以多種路徑的統一方式處理異常的最佳方法。

目前我有許多路由,它們都按以下方式處理異常:

...
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...
}

那么,是否存在用於異常處理的Spark-esque機制? 我查了一下文檔並做了簡短的介紹。 如果沒有,我會繼續我的重構計划。 謝謝。

你可以像這樣處理異常:

get("/throwexception", (request, response) -> {
    throw new NotFoundException();
});

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

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");
    }
}
}

然后(使用import static):

    get(wrap("/download", new DownloadHandler()));
    post(wrap("/upload", new UploadHandler()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM