2015-02-24 19 views
2

我們是Scalatra用戶。它 我想抽象出來:每次我們將創建一個servlet,我們將擴大我們的BaseServlet延伸ScalatraBase:從Scalatra切換到Spray:處理not spray和錯誤噴霧?

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中有沒有類似的方式可以處理我找不到的路徑和錯誤? 在此先感謝!

+0

請參閱噴塗文檔中的「拒收處理」和「異常處理」。 http://spray.io/documentation/1.2.2/spray-routing/key-concepts/rejections/ – jrudolph 2015-02-24 08:51:32

回答

1

你並不需要「抽象出來」,因爲在噴霧你沒有獨特的「小服務程序」 - 你只是一個路線,它可以調用其它路線:

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什麼。噴霧HttpServiceActor只處理一條路線,而不是一堆不同的「控制器」 - 這取決於你如何將所有路線組合成一條路線。

1

您必須定義一個自定義RejectionHandler。

在您的應用程序中將此RejectionHandler定義爲隱式的val。

import spray.routing.RejectionHandler 

private implicit val notFoundRejectionHandler = RejectionHandler { 
    case Nil => { 
    // If no route matches, then try to render a Scaml template... 
    } 
} 

我想通了自噴github上spec

+1

但我想把它抽象出來。我的意思是我想在我的BaseServlet中添加所有的錯誤和拒絕處理功能,然後擴展它(比如說AnyServlet)。因此,如果AnyServlet具有一個未被發現的路徑,或者在某處引發了一個異常,它將由BaseServlet自動處理。 – joanOfArc 2015-02-24 11:32:54

+0

我想你應該能夠在基類中定義拒絕處理程序。 – 2015-02-24 12:37:12