Skip to content

Latest commit

 

History

History
86 lines (66 loc) · 2.36 KB

02.5-backend-handling-exceptions.md

File metadata and controls

86 lines (66 loc) · 2.36 KB

Backend - Handling Exceptions

Creating the AppError Class

src/errors/AppError.ts:

class AppError {
  public readonly message: string;

  public readonly statusCode: number;

  constructor(message: string, statusCode = 400) {
    this.message = message;
    this.statusCode = statusCode;
  }
}

export default AppError;

Dealing with Errors

yarn add express-async-errors

Remove every try-catch clauses in the source files in src/routes/.

Replace every throw new Error() with throw new AppError().

In the src/server.ts AFTER use()ing the routes, add the global exception handler:

app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
  if (err instanceof AppError) {
    return response.status(err.statusCode).json({
      status: 'error',
      message: err.message,
    });
  }

  console.error(err);

  return response.status(500).json({
    status: 'error',
    message: 'Internal server error',
  });
});

Add this to .eslintrc.json (to ignore the unused vars "errors" in the editor):

// ...
  "rules": {
    // ...
    "@typescript-eslint/no-unused-vars": [
      "error",
      {
        "argsIgnorePattern": "_"
      }
    ]
  },
  // ...

Summary

  1. Install express-async-errors
  2. Create src/errors/AppError.ts:
  3. Remove every try-catch clauses in the source files in src/routes/
  4. Replace every throw new Error() with throw new AppError().
  5. In the src/server.ts AFTER use()ing the routes, add the global exception handler.

My GoBarber codebase up to this point

https://github.com/meleu/gobarber/tree/9c2a7a36b7950d2a53015466805a742bad6061de