How do I catch json parse error when using acceptW

2019-02-10 15:46发布

I use websockets with playframework 2.3.

This is a snippet from official how-to page.

def socket = WebSocket.acceptWithActor[JsValue, JsValue] { request => out =>
    MyWebSocketActor.props(out)
}

When I use the code, How do I catch json parse error(RuntimeException: Error parsing JSON)?

1条回答
2楼-- · 2019-02-10 16:20

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.

查看更多
登录 后发表回答