Created
October 14, 2019 12:34
-
-
Save jettary/b7c7eac7bd3937f7493497b8aededb9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.use(beforeControllersMiddlewares) | |
useExpressServer(app, { | |
routePrefix: '/api', | |
controllers: [`${__dirname}/controllers/*.ts`], | |
}); | |
app.use(afterControllersMiddlewares); | |
function afterControllersMiddlewares(err, req, res, next) { | |
if (err) { | |
// general error handler | |
if (err instanceof MyError) { | |
res.status(err.httpCode).json({ | |
code: err.verboseCode, | |
mesage: err.message, | |
}); | |
} else { | |
res.status(500).json({ | |
code: 'INTERNAL_SERVER_ERROR, | |
mesage: `Something went wrong: ${err.message}`, | |
}); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyError extends Error { // extends Error could works not so well | |
public httpCode: number; | |
puclic verboseCode: string; | |
constructor(httpCode, verboseCode, message) { | |
super(message); | |
this.httpCode = httpCode; | |
this.verboseCode = verboseCode; | |
} | |
} | |
controller(@Req() request: Request, @Res() response: Response) { | |
... | |
throw new MyError(401, 'UNAUTHENTICATED', 'Invalid username or password'); | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment