【问题标题】:How to handle exceptions for multiple Route如何处理多个路由的异常
【发布时间】:2012-11-28 12:42:42
【问题描述】:

我正在掌握Spark Framework,我正在尝试了解以统一方式为多个路由处理异常的最佳方法。

目前,我有许多 all 处理异常的路由:

...
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 的异常处理机制?我检查了文档并提出不足。如果没有,我将继续我的重构计划。谢谢。

【问题讨论】:

    标签: java exception-handling spark-java


    【解决方案1】:

    你可以像这样处理异常:

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

    示例取自Spark docs

    【讨论】:

      【解决方案2】:

      我一直在处理这个问题。这就是我想出的。它需要根据您的环境进行调整。

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

      【讨论】:

      • 嗨@Dan 我很想知道您需要在您的环境中进行哪些其他调整才能使其正常工作,因为我遇到了同样的问题。
      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      相关资源
      最近更新 更多