Error Handling
Moopsy makes it easy for you to throw and handle errors.
@moopsyjs/core
exports a MoopsyError
class. This is a special class, when you throw
a MoopsyError
on the server, it is considered client-safe and the full contents of the error will get sent down to the client. Any other errors that get thrown will get converted to this to prevent accidental leakage of sensitive information:
new MoopsyError(500, "internal-server-error", "Internal Server Error");
So let's say we have this endpoint:
server.endpoints.register<BP.Plug>(BP, async function (params, auth) {
if(!auth.private.isAdmin) {
throw new MoopsyError(403, "forbidden", "Access Denied");
}
// ...
});
Our client code can look like this:
const someMutation = moopsyClient.useMutation<SomeBP.Plug>(SomeBP);
// ...
someMutation.call({
some: "params"
}).then((res) => {
// do something with the response
}).catch((err) => {
if(err instanceof MoopsyError) {
// Alert the human readable error description
alert(err.description);
}
else {
// Something has seriously gone wrong...
}
});
In the above example we check if err
is an instance of MoopsyError
, but running .call()
on a mutation should
almost always throw a MoopsyError, regardless of what happens. Any other kind of error would be a severe edge-case.
For most use cases, we can assume the error is a MoopsyError.