How do I catch json parse error when using acceptWithActor?

家住魔仙堡 提交于 2019-11-30 15:22:21

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!