custom internal server error message in REST API
Hello all,
I am creating a REST API with a spec-first approach. However, I am using the try-catch method to handle any exception if any occurs. But whenever any error related to syntax or something occurs, we get internal server error
{
"errors": [
{
"code": 6220,
"domain": "%ObjectErrors",
"error": "ERROR #6220: Internal Server Error",
"id": "InternalError"
}
],
"summary": "ERROR #6220: Internal Server Error"
}
This is I think IRIS defined, I want to customize my own Internal server error.
Comments
Can you show us what you have coded in the catch block ? There should be no problem in handling your own error.
catch block looks something like this.
}catch (err){
do ..%SetStatusCode(500)
set res.stateCode = 500
set res.msg = "Server Internal Error"
set res.ErroMsg = err.%Message
return err
}
Assuming you are using generated disp and impl classes from a swagger document, the simplest option you have at the moment is to edit the code in the impl class:
- Use try/catch within your implementation method
- the catch block to set %response.Status = your required status code
- Create a json object with your required payload
- return this object instead of the usual payload object
This will bypass the default error handling of the disp class.
It isn't ideal though.
e.g.
ClassMethod myFunction(arg1 As %Integer) As %Stream.Object
{
try {
set ret = {"data": "value" }
if 1/0 // Force an error
}
catch err {
set ret = ##class(SomeClass).FormatError(err)
Set %response.Status = 500
}
quit ret
}However, it would be even more helpful to be able to override the default error display. This would need some changes to the dispatch and implementation class generators.
The dispatch class generator would need to call the specific implementation class to format the error, instead of the implementation superclass.
The implementation class generator also (really) needs to be able to accept an override for the implementation superclass via the swagger document (as there is for the dispatch class).
Then the try/catch would not be needed at all, and the default error handling would do everything needed.
This is as of Iris 2022.1. I'm not sure if this has been added in later versions.
I don't see dispatch classes in vs code. Also, Sharing a sample code for the same would be more helpful.
dispatch class, which just named disp next to impl class, is generated and generated classes are hidden by default and you can show them with a flag in the Server Explorer. But, this class always regenerates, when you compile your spec file.
have a look at this example, of how I deal with errors