Skip to content

Commit d3d1c39

Browse files
committed
Handle specfic errors at the controller level
1 parent 0028b6e commit d3d1c39

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export default class CourseAlreadyExists extends Error {
2+
constructor(courseId: string) {
3+
super(`Course ${courseId} already exists`);
4+
}
5+
}

src/apps/mooc_backend/controllers/CoursePutController.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Request, Response } from 'express';
22
import CreateCourse from '../../../Contexts/Mooc/Courses/application/CreateCourse';
33
import httpStatus from 'http-status';
44
import Controller from './Controller';
5+
import CourseAlreadyExists from '../../../Contexts/Mooc/Courses/domain/CourseAlreadyExists';
56

67
export default class CoursePutController implements Controller {
78
constructor(private createCourse: CreateCourse) {}
@@ -14,7 +15,13 @@ export default class CoursePutController implements Controller {
1415
try {
1516
await this.createCourse.run(id, name, duration);
1617
} catch (e) {
17-
res.status(httpStatus.INTERNAL_SERVER_ERROR).json(e);
18+
19+
if (e instanceof CourseAlreadyExists) {
20+
res.status(httpStatus.BAD_REQUEST).send(e.message);
21+
} else {
22+
res.status(httpStatus.INTERNAL_SERVER_ERROR).json(e);
23+
}
24+
1825
}
1926

2027
res.status(httpStatus.CREATED).send();

0 commit comments

Comments
 (0)