# Throw HTTP Exceptions

You can use @tsed/exceptions or similar module to throw an http exception. All exceptions will be intercepted by the Global error handler and are sent to the client.

Here is an example:

import {PathParams} from "@tsed/platform-params";
import {Get} from "@tsed/schema";
import {Controller} from "@tsed/di";
import {BadRequest} from "@tsed/exceptions";

@Controller("/calendars")
export class CalendarCtrl {
  @Get("/:id")
  get(@PathParams("id") id: number): any {
    if (isNaN(+id)) {
      throw new BadRequest("Not a number");
    }

    return {id};
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

TIP

This example will produce a response with status code 400 and "Not a number" message. GlobalErrorHandlerMiddleware will catch and format the error before sending it to the client.

# Create custom exception

It is also possible to create your own exception from any Exception of @tsed/exceptions and customize the response headers.

import {BadRequest} from "@tsed/exceptions";
import {ResponseErrorObject} from "@tsed/common";

export class RequiredUserName extends BadRequest implements ResponseErrorObject {
  headers = {};
  errors = [];

  constructor() {
    super("The name is required");
    this.headers["my-custom-header"] = "value";

    // you can also specify errors field for functional errors (like AJV validation).
    this.errors.push({
      dataPath: "",
      keyword: "required",
      message: "should have required property 'name'",
      modelName: "User",
      params: {
        missingProperty: "name"
      },
      schemaPath: "#/required"
    });
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Then in your controller:

import {Controller, Post, BodyParams} from "@tsed/common";
import {RequiredUserName} from "./RequiredUserName";
import {User} from "./models/User";

@Controller("/calendars")
export class CalendarCtrl {
  @Post()
  async create(@BodyParams() user: User): any {
    if (!user.name) {
      throw new RequiredUserName();
    }

    return user;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Last Updated: 2/11/2022, 7:27:21 PM

Other topics