Skip to content

Server Errors

Thiago Bustamante edited this page Jan 20, 2019 · 1 revision

Errors

This library provide some Error classes to map the problems that you may want to report to your clients.

Type Description
BadRequestError Used to report errors with status code 400.
UnauthorizedError Used to report errors with status code 401.
ForbiddenError Used to report errors with status code 403.
NotFoundError Used to report errors with status code 404.
MethodNotAllowedError Used to report errors with status code 405.
NotAcceptableError Used to report errors with status code 406.
ConflictError Used to report errors with status code 409.
InternalServerError Used to report errors with status code 500.
NotImplementedError Used to report errors with status code 501.

If you throw any of these errors on a service method, the server will log the problem and send a response with the appropriate status code and the error message on its body.

import {Errors} from "typescript-rest";

@Path("async")
class TestService {
   @GET
   @Path("test1")
   testGet() {
      return new Promise<MyClass>(function(resolve, reject){
         //...
      throw new Errors.NotImplementedError("This operation is not available yet");
      });
   }

   @GET
   @Path("test2")
   testGet2() {
      return new Promise<MyClass>(function(resolve, reject){
         //...
         reject(new Errors.NotImplementedError("This operation is not available yet"));
      });
   }

   @GET
   @Path("test3")
   testGet3() {
      throw new Errors.NotImplementedError("This operation is not available yet");
   }
}

All the three operations above will return a response with status code 501 and a message on the body This operation is not available yet

If you want to create a custom error that report your own status code, just extend the base class HttpError.

import {HttpError} from "typescript-rest";

class MyOwnError extends HttpError {
  constructor(message?: string) {
    super("MyOwnError", message);
    this.statusCode = 999;
  }
}

You must remember that all uncaught errors are handled by a expressjs error handler. You could want to customize it to allow you to inform how the errors will be delivered to your users. For more on this (for those who wants, for example, to send JSON errors), take a look at this question;