You can handle different types of HTTP errors by throwing specific error classes. Deepkit provides a number of built-in error classes for common HTTP errors, such as HttpNotFoundError
, HttpUnauthorizedError
, etc.
Here's an example:
import { HttpNotFoundError } from '@deepkit/http'; router.get('/user/:id', async (id: number, database: Database) => { const user = await database.query(User).filter({ id }).findOneOrUndefined(); if (!user) throw new HttpNotFoundError('User not found'); return user; });
In this example, if a user with the specified ID is not found, it will throw a HttpNotFoundError
with a status code of 404. Deepkit will handle the error and send an appropriate HTTP response.
You can also create your own custom error classes by extending the createHttpError
function exported by Deepkit.
export class HttpMyError extends createHttpError(412, 'My Error Message') { }