我们是 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/