Error Handling
Kaito handles errors gracefully throughout your application. You can throw errors anywhere in any route, and they will be automatically caught and processed. This allows you to focus on the happy-paths of your application while ensuring proper error handling. The other advantage to this pattern is that error messages containing sensitive information are never leaked, as everything passes through your onError handler.
Kaito has a built in error called KaitoError. You can throw this error in your routes, and it will be caught and sent back to the client.
import {KaitoError} from '@kaito-http/core';Throwing a KaitoError will not call your .onError handler defined in your server. KaitoErrors are handled
internally and are always sent back to the client.
export const users = router.get('/:id', async ({ctx, params}) => {
const user = await ctx.db.users.findOne({
where: {id: params.id},
});
if (!user) {
// Client will receive this status code and error message always. This bypasses your .onError() handler
throw new KaitoError(404, 'User not found');
}
return user;
});All other errors get forwarded to your .onError handler, which decides what status and message to send back to the client. If you have not defined an .onError handler, Kaito returns a 500 with "Internal Server Error".
WrappedError
If you throw a value that is not an Error (like a string or plain object), Kaito wraps it in a WrappedError before passing it to your .onError handler. You can access the original thrown value via .data.
import {WrappedError} from '@kaito-http/core';
const app = create({
// ...
onError: (error, req) => {
if (error instanceof WrappedError) {
console.log('Original thrown value:', error.data);
}
return {status: 500, message: 'Internal Server Error'};
},
});