Skip to content

Commit

Permalink
feat: add custom error handler (#285)
Browse files Browse the repository at this point in the history
* improvement: replace lib

* improvement: replace router for services

* feat: replace async routes

* feat: add custom error handler
  • Loading branch information
Achalhii committed Apr 29, 2024
1 parent 1ad4ee4 commit ed488a2
Showing 1 changed file with 25 additions and 22 deletions.
47 changes: 25 additions & 22 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,29 +149,32 @@ class CampsiServer extends MQTTEmitter {
this.app.use((req, res, next) => {
res.status(404).json({ message: `Can't find ${req.method} ${req.path}` });
});

this.app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}

// An error may happen in a middleware registred before the pino middleware.
if (req.log) {
req.log.error(err, err.message);
} else {
this.logger.error(err, err.message);
}

if (err instanceof ValidationError) {
return res.status(400).send(err.validationErrors);
}

const { message, status } = err;
res.status(status || 500).json({
message,
stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined
if (this.config.errorHandler) {
this.app.use(this.config.errorHandler(this));
} else {
this.app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}

// An error may happen in a middleware registred before the pino middleware.
if (req.log) {
req.log.error(err, err.message);
} else {
this.logger.error(err, err.message);
}

if (err instanceof ValidationError) {
return res.status(400).send(err.validationErrors);
}

const { message, status } = err;
res.status(status || 500).json({
message,
stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined
});
});
});
}
this.emit('campsi/ready');
}
}
Expand Down

0 comments on commit ed488a2

Please sign in to comment.