diff --git a/package.json b/package.json index 009cc65..91b7006 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ }, "dependencies": { "express": "^4.17.1", + "express-async-errors": "^3.1.1", "nodemailer": "^6.4.10", "uuidv4": "^6.2.0" }, diff --git a/src/app.ts b/src/app.ts index 707492a..bc0d6be 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,9 +1,17 @@ -import express from 'express' +import express,{ Request, Response, NextFunction } from 'express' +import 'express-async-errors' + import { router } from './routes' const app = express() app.use(express.json()) app.use(router) +app.use((err:Error, request: Request, response: Response, next: NextFunction) => { + if(err instanceof Error) { + return response.status(400).json({ message: err.message}) + } + return response.status(500).json({ message: 'Internal Server Error' }) +}) export { app } \ No newline at end of file diff --git a/src/routes.ts b/src/routes.ts index 759406a..335d931 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -3,8 +3,6 @@ import { createUserController } from "./useCases/CreateUser"; const router = Router() -router.post('/users', (request, response) => { - return createUserController.handle(request, response); -}); +router.post('/users', createUserController.handle); export { router } \ No newline at end of file diff --git a/src/useCases/CreateUser/CreateUserController.ts b/src/useCases/CreateUser/CreateUserController.ts index 5cd78ae..8d52a53 100644 --- a/src/useCases/CreateUser/CreateUserController.ts +++ b/src/useCases/CreateUser/CreateUserController.ts @@ -9,7 +9,7 @@ export class CreateUserController { async handle(request: Request, response: Response): Promise { const { name, email, password } = request.body; - try { + await this.createUserUseCase.execute({ name, email, @@ -17,10 +17,6 @@ export class CreateUserController { }) return response.status(201).send(); - } catch (err) { - return response.status(400).json({ - message: err.message || 'Unexpected error.' - }) - } + } } \ No newline at end of file