Scala错误处理中的错误上下文 [英] Error context in error handling in Scala

查看:119
本文介绍了Scala错误处理中的错误上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要调用远程JSON/HTTP服务.我发出一个JSON请求,通过HTTP将其发送到服务器,然后接收并解析JSON响应.

假设我的数据类型为MyError,并且我的所有函数都返回Either[MyError, R]

type Result[A] = Either[MyError, A]    

def makeJsonRequest(requestData: RequestData): Result[String] = ...

def invoke(url: URL, jsonRequest: String): Result[String] = ...

def parseJsonResponse(jsonResponse: String): Result[ResponseData] = ...

我可以将它们结合起来以编写新功能:

def invokeService(url: URL, requestData: RequestData) Result[ResponseData] = for {
   jsonRequest <- makeJsonRequest(requestData).right
   jsonResponse <- invoke(url, req).right 
   responseData <- parseJsonResponse(jsonResponse).right
} yield responseData

现在,如果parseJsonResponse失败怎么办?

我得到了错误,但我还需要整个 context .那就是我需要urlrequestDatajsonRequest.你会建议我怎么做?

解决方案

如果是特殊情况,我会将MyError设为特征(ADT),并允许其中一个可能的值为JsonParsingFailed(jsonRequest, ...)./p>

如果是更通用的东西,我可能会在每个阶段使用Writer(或更确切地说是type MyWriter[A] = Writer[Vector[MyLogEntry], A]然后使用EitherT[MyWriter, MyError, A])来记录事件".

Suppose I need to call a remote JSON/HTTP service. I make a JSON request, send it by HTTP to the server, and receive and parse the JSON response.

Suppose I have data type MyErrorfor errors and all my functions return Either[MyError, R]

type Result[A] = Either[MyError, A]    

def makeJsonRequest(requestData: RequestData): Result[String] = ...

def invoke(url: URL, jsonRequest: String): Result[String] = ...

def parseJsonResponse(jsonResponse: String): Result[ResponseData] = ...

I can combine them to write a new function:

def invokeService(url: URL, requestData: RequestData) Result[ResponseData] = for {
   jsonRequest <- makeJsonRequest(requestData).right
   jsonResponse <- invoke(url, req).right 
   responseData <- parseJsonResponse(jsonResponse).right
} yield responseData

Now what if parseJsonResponse fails ?

I get the error but I need also the whole context. That is I need url, requestData, and jsonRequest. How would you suggest me do it ?

解决方案

If this is a specific case I would make MyError into a trait (ADT), and allow one of the possible values to be JsonParsingFailed(jsonRequest, ...).

If it's something more generic I might use Writer (or rather type MyWriter[A] = Writer[Vector[MyLogEntry], A] and then use EitherT[MyWriter, MyError, A]) to "log the event" at every stage.

这篇关于Scala错误处理中的错误上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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