2012-11-28 62 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

嗨@丹我很想知道你需要什么其他调整你需要为了得到这个工作,因为我遇到了同样的问题。 –