- video: https://app.rocketseat.com.br/node/iniciando-back-end-do-app/group/tratando-excecoes/lesson/criando-classe-de-erro
- commit: https://github.com/rocketseat-education/bootcamp-gostack-modulos/commit/618b305f62a4e348a7e7a9ff4f14707d2131c440#diff-2efc37c87c194d03fc0dadbef51f8814
- goals:
- create a generic AppError class so we can define the HTTP status code in an easier way.
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;
- video: https://app.rocketseat.com.br/node/iniciando-back-end-do-app/group/tratando-excecoes/lesson/lidando-com-erros-2
- commit: https://github.com/rocketseat-education/bootcamp-gostack-modulos/tree/master/nivel-02/02-iniciando-back-end-do-app
- goals:
- create a middleware to handle all exceptions (global exception handler).
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": "_"
}
]
},
// ...
- Install
express-async-errors
- Create
src/errors/AppError.ts
: - Remove every try-catch clauses in the source files in
src/routes/
- Replace every
throw new Error()
withthrow new AppError()
. - In the
src/server.ts
AFTERuse()
ing the routes, add the global exception handler.
https://github.com/meleu/gobarber/tree/9c2a7a36b7950d2a53015466805a742bad6061de