# Customize 404

The guide shows you how you can customize the 404 response error when a resource or route isn't resolved by the router.

Customizing error is possible by using the Exception filter feature and by catching the ResourceNotFound error class. This error is thrown by Ts.ED when nothing routes are resolved.

Create a new ResourceNotFoundFilter in the filters directories and copy/paste this example:

import {Catch, ExceptionFilterMethods, PlatformContext, ResourceNotFound} from "@tsed/common";

@Catch(ResourceNotFound)
export class ResourceNotFoundFilter implements ExceptionFilterMethods {
  async catch(exception: ResourceNotFound, ctx: PlatformContext) {
    const {response} = ctx;

    const obj = {
      status: exception.status,
      message: exception.message,
      url: exception.url
    };
    // Json response
    response
      .status(exception.status)
      .body(obj);

    // Or with ejs/handlers/etc...
    await response
      .status(exception.status)
      .render("404.ejs", obj);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

WARNING

response.render() require to configure the template engine before. See our page over Templating engine installation for more details.

Then import the custom filter in your server:

import {Inject} from "@tsed/di";
import {Configuration, PlatformApplication} from "@tsed/common";
import "./filters/ResourceNotFoundFilter"; // Importing filter with ES6 import is enough

@Configuration({
  // ...
})
export class Server {
}
1
2
3
4
5
6
7
8
9

Last Updated: 1/14/2021, 10:28:24 AM

Other topics