0

I'm creating a rest api for a work project using fastify, i'm far enough into the project where I'm starting to figure out error handling in my project. However, I can't seem to get my head wrapped around how to implement error handling properly in fastify. For instance how do I change the structure of the default error messages? I've seen some examples where custom response schema layouts are used, but is that used for to changes the structure of the responses or is it purely for response validation? Furthermore, I've also seen examples either throw error objects when defining custom errors, but I've also seen examples that use functions that are apart of the request object when throwing errors. What's the difference between the two methods for throwing custom errors? Any advice on how deal with this issue is appreciated.

TechEmperor95
  • 389
  • 1
  • 4
  • 18

1 Answers1

4

By default fastify can handle error when they are thrown to setErrorHandler method. In these case the setErrorHandler has error property and the error property expects statusCode, message properties in it. So I managed to extend the Error property to use it. You can see the below code to make you clear

    class ApiError extends Error {
  constructor(statusCode, message) {
    super(message);
    this.statusCode = statusCode;

    Error.captureStackTrace(this, this.constructor);
  }
}

We can use the ApiError like in

const product = await Product.findOne({ _id: productId });
  if (!product) {
    throw new ApiError(httpStatus.NOT_FOUND, 'Product not found');
  }

So when an unHandled Promise error is thrown the setErrorHandler method will send the custom http-status code and message that we defined in the ApiError

If you throw the default Error with a message

throw new Error('Product not found');

like these the error handler will return statusCode of 500 ( Internal Server Error ) and with a message of 'something went wrong'

To know more about the setErrorHandler method you can have reference from official docs https://www.fastify.io/docs/latest/Reference/Server/#seterrorhandler

Sathish
  • 41
  • 4