HttpException

Notice: It is mainly for REST applications.

Nest has error handling layer, which catches all unhandled exceptions.

If - somewhere - in your application, you will throw an Exception, which is not HttpException (or inherited one), Nest will handle it and return to user below json object (500 status code):

{
  "message": "Unkown exception"
}

Exception Hierarchy

In your application, you should create your own Exceptions Hierarchy. All 'HTTP exceptions' should inherit from built-in HttpException.

For example, you can create NotFoundException and UserNotFoundException classes:

import { HttpException } from '@nestjs/core';

export class NotFoundException extends HttpException {
    constructor(msg: string | object) {
        super(msg, 404);
    }
}

export class UserNotFoundException extends NotFoundException {
    constructor() {
        super('User not found.');
    }
}

Then - if you somewhere in your application throw UserNotFoundException, Nest will response to user with status code 404 and above json object:

{
  "message": "User not found."
}

It allows you to focus on logic and make your code much easier to read.

results matching ""

    No results matching ""