使用acceptWithActor时如何捕获json解析错误? [英] How do I catch json parse error when using acceptWithActor?

查看:124
本文介绍了使用acceptWithActor时如何捕获json解析错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在playframework 2.3中使用了websockets.

I use websockets with playframework 2.3.

这是官方操作页面的摘录.

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

使用代码时,如何捕获json解析错误(RuntimeException:解析JSON错误)?

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

推荐答案

使用内置的json帧格式化程序,您不能这样做,这是源代码:

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

如果Json.parse引发异常,它将将该异常引发给Netty,这将警告Netty异常处理程序,该处理程序将关闭WebSocket.

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.

您可以做的是定义自己的处理异常的json帧格式化程序:

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)
}

然后,您可以在WebSocket actor中检查具有错误字段的json消息,然后根据自己的意愿对其进行响应.

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.

这篇关于使用acceptWithActor时如何捕获json解析错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆