How do I catch json parse error when using acceptWithActor?

好久不见. 提交于 2019-11-30 15:53:23

问题


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:


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.



来源:https://stackoverflow.com/questions/26006968/how-do-i-catch-json-parse-error-when-using-acceptwithactor

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