# 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 {PlatformContext, ResourceNotFound} from "@tsed/common";
import {Catch, ExceptionFilterMethods} from "@tsed/platform-exceptions";

@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...
    const html = await response.render("404.ejs", obj);
    response.status(exception.status).body(html);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

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

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

Other topics