1.0.14 • Published 3 years ago

@yilmazcik/common v1.0.14

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

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

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago