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

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

问题描述

我在 playframework 2.3 中使用 websocket.

I use websockets with playframework 2.3.

这是来自官方操作方法页面的片段.

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

当我使用代码时,如何捕捉json解析错误(RuntimeException: Error parsing 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 将提醒 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天全站免登陆