What are the pros and cons of using the default Error object this way? If I can already use it like this, why should I create custom error object (class CustomError extends Error {...})?
import express from 'express';
const app = express();
// routes
app.get('/one', (req, res, next) => {
const error = new Error();
error.code = 400;
error.message = 'Any error message for /one';
next(error);
});
app.get('/two', (req, res, next) => {
// Async example
setTimeout(() => {
try {
throw new Error();
} catch (error) {
error.code = 403;
error.message = 'Any error message for /two';
next(error);
}
}, 1000);
});
app.get('/three', (req, res, next) => {
throw new Error('Random unexpected');
});
// error handling middlewares
app.use((error, req, res, next) => {
console.log('ERROR LOGGER');
console.log('Date: ', new Date(Date.now()).toLocaleString());
console.log('Path: ', req.path);
console.log('Status Code: ', error.code || 500);
console.log('Message: ', error.message || 'internal server error');
console.log('Error: ', error);
next(error);
});
app.use((error, req, res, next) => {
res.status(error.code || 500).json({ code: res.statusCode, message: error.message || 'internal server error' });
});
// Listen Port
app.listen(3000);
Responses and Logs:
/one
/two
/three
By creating such a custom Error object
class HttpError extends Error {
constructor(name, code, message) {
super();
this.name = name;
this.code = code;
this.message = message;
}
}
export default HttpError;
has the advantage of both having central control and preventing excessive repetition:
import HttpError from './HttpError.js';
.
.
.
app.get('/one', (req, res, next) => {
next(new HttpError('Name errOne', 400, 'Any error message for /one'));
});
.
.
app.get('/two', (req, res, next) => {
// Async example
setTimeout(() => {
try {
throw new HttpError('Name errTwo', 403, 'Any error message for /two');
} catch (error) {
next(error);
}
}, 1000);
});