- Express error middleware with custom error types for easy error handling for different use cases.
- If you are not using express then you can still use the custom error types. But then they will only throw the error and it will not be sended to the client!
import axios from 'axios'
import express from 'express'
import 'express-async-errors'
import { errorMiddleware, HttpClientError } from 'error-manager-helper'
const app = express()
// Sample route to trigger custom error HttpClientError
app.get('/httpclient-error', async() => {
try {
await axios.get(`${BASE_URL}/notFound`)
} catch (err) {
throw new HttpClientError('Any error message..', err)
}
})
// Include error middleware
app.use(errorMiddleware)
const server = app.listen(port)
console.log(`Server is running on port ${port}`)
- Will be always HTTP Status 500
- Passing error is optional
throw new BaseError('Your error message', new Error('Any Error'))
-
At the moment working with those HTTP clients:
- axios
-
Will be the status of the error of your HTTP request
try {
await axios.get(`${BASE_URL}/notFound`)
} catch (e) {
throw new HttpClientError('Your error message', e)
}
- Will be always HTTP Status 400
- Passing error is optional
throw new ValidationError('Your error message', { dataThatNotValid }, new Error('Any Error'))
- Will be always HTTP Status 404
- Passing error is optional
throw new ResourceNotFoundError('Your error message', dataThatMissed, new Error('Any Error'))
- You can define custom HTTP status
- Passing error is not optional
throw new RuntimeError('Your error message', errorHere, customHttpStatus)
- Some errors may leak sensitive informations in the error itself or by the additional provided data object which you include to your custom error e.g.
throw new ValidationError('Your error message', { objectWithPw }, new Error('Any Error'))
.- For this reason when you use
npm_lifecycle_event=start
then your providederror, data and stack trace will be sanitized
and not sended to the client. Sample response:
- For this reason when you use
{
"environment": "start",
"message": "collection name 'test!' can not contain special characters",
"httpStatus": 500,
"error": '[SANITIZED]',
"data": '[SANITIZED]',
"stack": '[SANITIZED]'
}
- With all other npm_lifecycle_event it will be not sanitized. However, even with npm_lifecycle_event=start the full error will logged with console.error.