How do I catch json parse error when using acceptWithActor?

后端 未结 1 2070
一个人的身影
一个人的身影 2021-01-03 06:17

I use websockets with playframework 2.3.

This is a snippet from official how-to page.

def socket = WebSocket.acceptWithActor[JsValue, JsValue] { requ         


        
相关标签:
1条回答
  • 2021-01-03 06:43

    Using the built in json frame formatter, you can't, here's the source code:

    https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/mvc/WebSocket.scala#L80

    If Json.parse throws an exception, it will throw that exception to Netty, which will alert the Netty exception handler, which will close the WebSocket.

    What you can do, is define your own json frame formatter that handles the exception:

    import play.api.mvc.WebSocket.FrameFormatter
    
    implicit val myJsonFrame: FrameFormatter[JsValue] = implicitly[FrameFormatter[String]].transform(Json.stringify, { text => 
      try {
        Json.parse(text)
      } catch {
        case NonFatal(e) => Json.obj("error" -> e.getMessage)
      }
    })
    
    def socket = WebSocket.acceptWithActor[JsValue, JsValue] { request => out =>
      MyWebSocketActor.props(out)
    }
    

    In your WebSocket actor, you can then check for json messages that have an error field, and respond to them according to how you wish.

    0 讨论(0)
提交回复
热议问题