Questions & Answers

How can I handle different types of HTTP errors?

Deepkit HTTP
50 up-votes
Warning: The answer is generated by an artificial intelligence. It might not be correct.
To adjust rating, open the thread in Discord and click on the up/down vote button.

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') {
}