如何在Scala中编写处理期货异常的函数?

时间:2016-05-04 07:27:51

标签: scala

在我的申请中,我多次以同样的方式处理未来的错误。

例如我这样做:

def handleException(): PartialFunction[Throwable, Unit] = {
  case arithmeticException => log("arithmetic exception")
  case NonFatal(e) => log(e)
}

如何从恢复部分中提取方法以便在其他地方重用它?

例如,我想做类似的事情:

future map(r => println(r)) recover { handleException() }

并像这样使用它:

Public Overrides Function SaveChanges() As Integer

    ChangeTracker.DetectChanges()
    Dim ctx As ObjectContext = DirectCast(Me, IObjectContextAdapter).ObjectContext

    Dim objectStateEntryList As List(Of ObjectStateEntry) = ctx.ObjectStateManager.
        GetObjectStateEntries(EntityState.Added Or EntityState.Modified Or EntityState.Deleted).ToList()

    For Each ent As ObjectStateEntry In objectStateEntryList
        If Not ent.IsRelationship Then
            Dim objectType As Type = ObjectContext.GetObjectType(ent.Entity.GetType)
            Dim audit As New Audit With {
                .ObjectId = ent.EntityKey.EntityKeyValues.First.Value,
                .ObjectType = ObjectContext.GetObjectType(ent.Entity.GetType).Name,
                .User = (From u In Users Where u.Username = My.User.Name).First
            }
            With audit
                Select Case ent.State
                    Case EntityState.Added
                        .Action = "Created"
                        .Detail = "Record created"
                    Case EntityState.Deleted
                        .Action = "Deleted"
                        .Detail = "Record deleted"
                    Case EntityState.Modified
                        Dim newObj As String = SerializeToString(
                            Convert.ChangeType(ent.Entity, objectType)
                        )
                        .Action = "Modified"
                        .Detail = newObj.ToString
                End Select
            End With
        End If
    Next

    Return MyBase.SaveChanges()

End Function

我该怎么做?

1 个答案:

答案 0 :(得分:1)

val handleException: PartialFunction[Throwable, Unit] = {
  case arithmeticException => log("arithmetic exception")
  case NonFatal(e) => log(e)
}

future.map(println).recover(handleException)