-
Notifications
You must be signed in to change notification settings - Fork 6
Handle errors
A custom ApiError error class is available in appError
It extends the base nodeJS Error class, and add an HTTP status code to it
You can extend this class to implement your own custom errors
// Custom ApiError, modifying its behavior
class FileNotFoundError extends ApiError {
constructor(path: str) {
super(StatusCodes.NOT_FOUND, `File ${path} not found`);
}
}
throw new FileNotFoundError('./test'); // Will reply with a 404Every errors are catched thanks to the central errorMiddleware
It means you can safely throw anywhere in your controllers
The API will automatically catch any error and respond with the according HTTP code and message
import createError from 'http-errors'
import httpStatus from 'http-status-codes';
import { ApiError } from './appErrors';
export async function createPost(payload) {
if (...) {
throw new ApiError(httpStatus.UNAUTHORIZED, 'What\'s the point in coding now ?');
}
}Every responses going out of the API inherits from the same interface: the RO (Response Object). The errorMiddleware automatically format them
interface Ro {
error?: {
statusCode: number;
message: string;
};
}It ensures maximal coherence and the thanks of the front-end team
If any of your route crashes, for a reason or another, the error will still be catched by the error middleware.
It will be printed to error output (to help developers solving the issue), and converted into a 500 - Internal server error response