Question
· Dec 19, 2019

%New error handling

Hi,

On a persistent class, I have defined an %OnNew method that validate some properties with appropriate status code for each kind of error.
Question is: how do you catch the specific error when %New is called on this class?

Surrounding %New method with a try-catch not seems to work.

Thanks

Discussion (8)4
Log in or sign up to continue

I've changed my recommendation on this a little. Return the result of %ValidateObject() as the final argument, but don't return that status as the return value of the method. That way, if there are any required properties, and the call to %New() doesn't supply them, %OnNew() still works. Here's the updated example:

/// constructor
Method %OnNew(name As %String = "", phone As %String = "", dob as %Date, Output valid As %Status) As %Status [Private]
{
    set valid = $$$OK
    set ..Name = name
    set ..Phone = phone
    set ..DOB = dob
    set valid = ..%ValidateObject() // validate the new object
    return $$$OK
}

%OnNew() must return a %Status to %New(). But the code that calls %New() also needs the %Status. I think a "best practice" is simply to add an Output  %Status argument to %OnNew() that will therefore be returned to %New(). So the %Status is being returned using return (for %New()) and by using a pass-by-reference argument (for the code that calls %New()).

/// constructor
Method %OnNew(name As %String = "", phone As %String = "", dob as %Date, Output st As %Status) As %Status [Private]
{
    set st = $$$OK
    set ..Name = name
    set ..Phone = phone
    set ..DOB = dob
    set st = ..%ValidateObject() // validate the new object
    return st
}

Hi Blaise,

You can pass %OnNew expection to %New with this code snippet :

Class Test.PersitenceTest Extends %Persistent
{
 
Property mandatory As %String [ Required ];
 
Method %OnNew(mandatory As %String = "") As %Status
{
 
set ..mandatory = mandatory
 
$$$ThrowOnError(..%ValidateObject())
 
Quit $$$OK
}
 
}

 Now when you call the new method :

USER>set test = ##class(Test.PersitenceTest).%New()

  If $isobject($get(newerror))=1 Throw newerror
                                 ^
<THROW>%Construct+9^Test.PersitenceTest.1 *%Exception.StatusException ERROR #5659: Property 'Test.PersitenceTest::mandatory(10@Test.PersitenceTest,ID=)' required

Now you can catch you %OnNew expection anywhere :

ClassMethod test() As %Status
{
try {
set test = ##class(Test.PersitenceTest).%New()
}
catch ex {
Return ex.AsStatus()
}
Return $$$OK
}