@yilmazcik/common
TypeScript icon, indicating that this package has built-in type declarations

1.0.14 • Public • Published

This is an npm package that includes shared code used betweeen other services:

Error Handling with Typescript

In microservices, every service can be made by different programming languages so each service might have a different response structures. Eventually all those responses will go to the same front end application, in my project to react application. Inside of react app, we have to encode the knowledge of how to work with these different kinds of error responses. React app is going to have to know all the different error responses. We need to make absolutely sure every single service is going to send back an identical looking structure.

In typescript we cannot add custom properties to the error object but we need to add some more custom properties to 'Error'. That means we need to subclass Error. We take the built-in Error object, we are going to subclass into some separate subclasses, like RequestValidationError or DatabaseConnectionError. When we create subclasses we can add in some additional custom properties to it that will further clarify the reason for the error.

Create abstract CustomError:

export abstract class CustomError extends Error {
  abstract statusCode: number;
  constructor(message: string) {
    super(message);
    // Only because we are extending a built in class
    Object.setPrototypeOf(this, CustomError.prototype);
  }
  //   this is not a method. it is a method signature. abstract class should have at least one method
  abstract serializeErrors(): { message: string; field?: string }[];
}

Abstract classes are mainly for inheritance where other classes may derive from them. We cannot create an instance of an abstract class. Abstract classes are implemented as regular classes in the JavaScript generated by the TypeScript compiler. The drawback of this approach is that it is the TypeScript compiler that prevents abstract classes from being instantiated, and this isn’t carried over into the JavaScript code, potentially allowing objects to be created from the abstract class. However, this approach does mean that the instanceof keyword can be used to narrow types. All other subclasses inside "/error" will inherit from CustomError.

Then we write our express middleware for error handling:

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // We categorized some errors under CustomERror
  if (err instanceof CustomError) {
    return res.status(err.statusCode).send({ errors: err.serializeErrors() });
  }
  // this is for debugging. In case I forgot some error other than CustomError
  console.error(err);
  res.status(400).send({ message: "Unexpected Error" });
};
  • express is aware of number of arguments that are going into a middleware. If we have a middleware function with 4 arguments express is going to assume that this is a function meant to handle errors. Wherever we throw an error inside our app, this middleware will catch them.

in services , after all route handlers we are going to use this middleware:

app.all("*", async (req, res, next) => {
  // next() is necessary for handling async errors. if we had only sync errors: throw new NotFoundError
  //   next(new NotFoundError());
  // express-async-errors will help this error to be resolved without next()

  throw new NotFoundError();
});

npm i express-async-errors

all we have to do import it: import "express-async-errors"

Events in microservices

Readme

Keywords

none

Package Sidebar

Install

npm i @yilmazcik/common

Weekly Downloads

0

Version

1.0.14

License

ISC

Unpacked Size

28.4 kB

Total Files

44

Last publish

Collaborators

  • yilmazito