文章
Michael Lei · 八月 9 阅读大约需 2 分钟

ObjectScript 错误处理片段

ObjectScriptt至少有三种处理错误的方法(状态代码status codes、异常 exceptions, SQLCODE等)。大多数系统代码使用状态码,但由于一些原因,异常更容易处理。在处理遗留代码时,你要花一些时间在不同的技术之间进行转换。我经常使用这些片段作为参考。希望它们对其他人也是有用的。

 

///Status from SQLCODE:
set st = $$$ERROR($$$SQLError, SQLCODE, $g(%msg))  //embedded SQL
set st = $$$ERROR($$$SQLError, rs.%SQLCODE, $g(rs.%Message)) //dynamic SQL
///Exception from SQLCODE:
throw ##class(%Exception.SQL).CreateFromSQLCODE(SQLCODE,%msg) //embedded SQL
throw ##class(%Exception.SQL).CreateFromSQLCODE(rs.%SQLCODE,rs.%Message) //dynamic SQL
throw:(SQLCODE'=0)&&(SQLCODE'=100) ##class(%Exception.SQL).CreateFromSQLCODE(SQLCODE,%msg) //don't throw if query succeeds or finds no data 
///Exception from status:
$$$ThrowOnError(st)
///Status from exception:
set st = err.AsStatus()
///Creating a custom error status:
set st = $$$ERROR($$$GeneralError,"Custom error message")
///Throwing a custom exception:
$$$ThrowStatus($$$ERROR($$$GeneralError,"Custom error message"))
///Handling a SOAP error with a status:
try {
  //SOAP request code
} Catch err {
  If err.Name["ZSOAP" {
    Set st = %objlasterror
  } Else {
    Set st = err.AsStatus()
  }
}
return st
///Defining a custom exception class
Class App.Exceptions.SomeException Extends %Exception.AbstractException
{
Method OnAsStatus() As %Status
{
  return $$$ERROR($$$GeneralError,"Custom error message")
}
}
///Throwing and catching a custom exception
try {
  throw ##class(App.Exceptions.SomeException).%New()
} catch err {
  if err.%ClassName(1) = ##class(App.Exceptions.SomeException).%ClassName(1) {
    //some handling unique to this type of exception
  }
}
0
0 30
讨论 (0)1
登录或注册以继续