scala - 从 Scalatra 切换到 Spray : Handling notFound and errors in spray?

标签 scala servlets spray scalatra

我们是 Scalatra 用户。每次我们创建一个 servlet 时,我们都会扩展 BaseServlet,从而扩展 ScalatraBase:

    trait BaseServlet extends ScalatraFilter with ScalateSupport with FlashMapSupport  {

      /**
       * Returns the request parameter value for the given argument.
       */
      def getParam(key:String)(implicit request: HttpServletRequest): Option[String] = Option(request.getParameter(key))

      notFound {
        // If no route matches, then try to render a Scaml template
        val templateBase = requestPath match {
          case s if s.endsWith("/") => s + "index"
          case s => s
        }
        val templatePath = "/WEB-INF/templates/" + templateBase + ".scaml"
        servletContext.getResource(templatePath) match {
          case url: URL =>
            contentType = "text/html"
            templateEngine.layout(templatePath)
          case _ =>
            filterChain.doFilter(request, response)
        }
      }

      error {
        case e:ControlThrowable => throw e
        case e:Throwable =>
          val errorUID:String =  UUID.randomUUID.getLeastSignificantBits.abs.toString
          Log.logger(Log.FILE.ALL_EXCEPTIONS).error("#"+ errorUID + " -- " + e.getMessage + e.getStackTraceString)
          contentType = "application/json"
          response.setStatus(500)
          JsonUtility.toJSONString( Map("message" ->  ("Server Error # "+ errorUID  ) ,  "reason" -> e.getMessage ))
      }
}

编辑: 我想把它抽象出来。我的意思是我想在我的 BaseServlet 中添加所有错误和拒绝处理功能,然后扩展它(比如说 AnyServlet)。因此,如果 AnyServlet 未找到路径或在某处抛出异常,它会由 BaseServlet 自动处理。 Spray 中是否有类似的东西可以以类似的方式处理未找到的路径和错误? 提前致谢!

最佳答案

您不需要“将其抽象出来”,因为在 Spray 中您没有独特的“servlet” - 您只有一条路线,它可能会调用其他路线:

class UserRoute {
  val route: Route = ...
}
class DepartmentRoute {
  val route: Route = ...
}
class TopLevelRoute(userRoute: UserRoute, departmentRoute: DepartmentRoute) {
  val route: Route =
    (handleRejections(MyRejHandler) & handleExceptions(MyExHandler)) {
      path("users") {
        userRoute.route
      } ~
      path("departments") {
        departmentRoute.route
      }
    }
}

您可以将处理程序放在 TopLevelRoute 中,它将应用于 UserRoute 或 DepartmentRoute 中的任何内容。 Spray HttpServiceActor 仅处理单个路由,而不是一堆不同的“ Controller ” - 这取决于您如何将所有路由合并为单个路由。

关于scala - 从 Scalatra 切换到 Spray : Handling notFound and errors in spray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691019/

相关文章:

tomcat - 如何使用 xsbt-web-plugin 为每个 Spray 应用程序启动具有不同端口的多个 Tomcat 实例?

scala - 使用 BasicAuth 进行喷射身份验证方法

scala - 在 Scala 中创建星期几枚举的​​简洁方法

scala - "close"一个流?

java - 如何获取正在上传的文件的 InputStream 的 MIME 类型?

java - 谁能修复 jsp 和 servlet 中的删除功能吗?

scala - 将 Future[Object] 转换为 Future[S]

java - http 获取正文请求

java - JSP和Spring MVC的多个复选框,如何获取值

scala - 喷雾测试 gzip 解码