2012-11-28 60 views
5

我正在處理Spark Framework,我試圖理解以統一方式處理多個路由異常的最佳方式。如何處理多個路由的例外情況

目前,我有一些路線的其中所有處理異常的線沿線的:

... 
catch (final Exception e) { 
    ... 
    response.status(418); 
    return e.getMessage(); 
} 
... 

這留下了很多有待改進,主要是異常邏輯在它們之間複製。我知道,它可以通過重構得到改善,但我想知道是否有類似彈簧的ExceptionHandler機制,其中當一個特定的異常被拋出,你可以執行的操作,如東西:

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

那麼,有沒有一個用於異常處理的Spark-esque機制?我已經檢查了文檔並且簡短地介紹了一下。如果沒有,我會繼續我的重構計劃。謝謝。

+0

@ david99world標記[spark]的描述與這個新的火花框架無關。標籤需要重新定義或者必須爲此創建新的標籤。 –

+0

@ david99world我試着添加一個'spark-framework'標籤,但沒有足夠的代表,我想它說1.5k是必需的。 – Jonathan

回答

7

您可以處理異常,像這樣:從Spark docs採取

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

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

例。

0

我一直在處理這個問題。這是我想出的。它需要調整你的環境。

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())); 
+0

嗨@丹我很想知道你需要什麼其他調整你需要爲了得到這個工作,因爲我遇到了同樣的問題。 –