spray-routing中的Exception Handling

来源:互联网 发布:数据建模是什么 编辑:程序博客网 时间:2024/05/16 06:48

使用ExceptionHandler来处理异常

当spray-routing出现问题时我们可以使用ExceptionHandler来隐式来优雅的处理异常

trait ExceptionHandler extends PartialFunction[Throwable, Route]

由这个偏函数就可以知道,其实就是一个Throwable到Route的映射关系

我们创建一个简单的服务让他在处理请求时抛出by zero异常,即算数异常

class MyService extends HttpServiceActor {  implicit val myRejectionHander = RejectionHandler{    case MissingCookieRejection(cookieName) :: _ =>      complete(BadRequest, "No cookies, no service!!!")  }  implicit  def myExceptionHander(implicit log:LoggingContext) = ExceptionHandler {    case e : ArithmeticException =>      requestUri { uri =>        log.warning("Request to {} could not be handled normally", uri)        complete(InternalServerError, "Bad numbers, bad result!!!")      }  }  lazy val a = 12 / 0  def receive = runRoute {    //指定一个Path,用来配置URL和结果    path("order") {      get {        complete(s"Received GET ${a}")      } ~        post {          decodeRequest(Gzip) {            complete("Received POST")          }        }    }  }}

在异常中我们可以发现程序把异常捕获处理后以自定义的response返回给客户,(spray web是制作基于json的Rest的很好选择)

启动

object ActorTest4 extends App{  implicit val system = ActorSystem("mySystem")  val MyService = system.actorOf(Props[MyService])  implicit val timeout = Timeout(5.seconds)  IO(Http) ! Http.Bind(MyService,interface = "localhost",port=8080)}



 

 

0 0
原创粉丝点击