使用acceptWithActor时如何捕获json解析错误?

时间:2022-12-01 18:13:13

I use websockets with playframework 2.3.

我使用带有playframework 2.3的websockets。

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

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

1 个解决方案

#1


6  

Using the built in json frame formatter, you can't, here's the source code:

使用内置的json帧格式化器,你不能,这里是源代码:

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.

如果Json.parse抛出异常,它会将该异常抛出到Netty,这将提醒Netty异常处理程序,它将关闭WebSocket。

What you can do, is define your own json frame formatter that handles the exception:

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

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.

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

#1


6  

Using the built in json frame formatter, you can't, here's the source code:

使用内置的json帧格式化器,你不能,这里是源代码:

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.

如果Json.parse抛出异常,它会将该异常抛出到Netty,这将提醒Netty异常处理程序,它将关闭WebSocket。

What you can do, is define your own json frame formatter that handles the exception:

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

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.

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