Skip to content

Error Handling

In this section, we will demonstrate how to handle errors in an Axe API project.

  • You will learn
  • What is error handling?
  • Which HTTP status codes are used by Axe API?
  • How Axe API handles errors?
  • How to send a custom error in hooks?

Motivation

Error handling in REST APIs involves managing and communicating errors that occur during API interactions. It includes providing informative error responses, appropriate HTTP status codes, and error messages to help clients understand and handle errors effectively.

Axe API provides a common error structure for all endpoints that are generated by model definition. It uses HTTP status codes actively. Also, Axe API provides a common response structure for both validation and custom errors.

HTTP status codes

Axe API provides the following status codes for all auto-generated routes;

200

It means that everything is fine and no error was found.

bash
$ curl --head http://localhost:3000/api/v1/users
bash
HTTP/1.1 200 OK
Content-Language: en
Content-Type: application/json; charset=utf-8
Date: Thu, 18 May 2023 15:34:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5

400

It means that the HTTP client sent unacceptable data. It can be thrown by Axe API directly due to form validation, like the following example;

bash
$ curl --head -X POST http://localhost:3000/api/v1/users
bash
HTTP/1.1 400 Bad Request
Content-Language: en
Content-Type: application/json; charset=utf-8
Date: Thu, 18 May 2023 15:34:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
json
{
  "errors": {
    "email": ["The email field is required."],
    "name": ["The name field is required."],
    "surname": ["The surname field is required."]
  }
}

On the other hand, in some cases, Axe API might use the ApiError class to throw an error message like the following example;

ts
throw new ApiError(`Unacceptable query parameter: ${value}`);

In this case, the error message is returned with both a 400 HTTP Status Code and the following response body.

bash
$ curl \
  -H "Content-Type: application/json" \
  -X GET "http://localhost:3000/api/v1/users?fields=xxx"
bash
HTTP/1.1 400 Bad Request
Content-Language: en
Content-Type: application/json; charset=utf-8
Date: Thu, 18 May 2023 15:34:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
json
{ "error": "Undefined column names: xxx" }

404

It means that the resource is not found on the API.

bash
$ curl \
  -H "Content-Type: application/json" \
  -X GET "http://localhost:3000/api/v1/users/999"
bash
HTTP/1.1 400 Bad Request
Content-Language: en
Content-Type: application/json; charset=utf-8
Date: Thu, 18 May 2023 15:34:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
json
{ "error": "The item is not found on User." }

Error handler

Axe API provides an error handler in all Axe API projects as default like the following one;

ts
import { IncomingMessage, ServerResponse } from "http";
import { NextFunction } from "http";

const ErrorHandler = (
  err: any,
  req: IncomingMessage,
  res: ServerResponse,
  next: NextFunction,
) => {
  if (process.env.NODE_ENV === "production") {
    // Send errors to your error monitoring tool like Sentry
  }

  // Sett the HTTP status code
  res.statusCode = 500;

  // Set the default HTTP message
  res.write(
    JSON.stringify({
      error: "Internal server error",
    }),
  );

  res.end();
  next();
};

export default ErrorHandler;

You can edit the ErrorHandler.ts file by your logic.

But you should define the error handler via the app/config.ts file.

ts
import { IApplicationConfig } from "axe-api";
import errorHandler from "./ErrorHandler";

const config: IApplicationConfig = {
  // ...
  errorHandler,
  // ...
};

Custom errors

Axe API provides a standard error message structure to you via the ApiError class. You can throw an error in your hooks like the following example;

ts
import { ApiError, StatusCodes } from "axe-pi";

export default async () => {
  throw new ApiError("My custom error!", StatusCodes.FORBIDDEN)
};
bash
$ curl http://localhost:3000/api/v1/users
bash
HTTP/1.1 403 OK
Content-Language: en
Content-Type: application/json; charset=utf-8
Date: Thu, 18 May 2023 15:34:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
json
{
  "error": "My custom error!"
}

Next steps

In this section, we tried to explain all details of error handling. You can check the API Reference section to get more information about it.

In the next section, we are going to talk about a very important thing: how to add your business logic.

Released under the MIT License.