Have you ever experienced this error before or are you experiencing it now? I'll be honest and say I experienced it more than once but I didn't care so much at first. This error is normally thrown by the express body-parser as a syntax error. If you have a global error handler in your app, the error will always be sent to the user as an internal server error with status code 500. But you have a problem with that, don't you? Yes, so do I.
Why do we have a problem if it will be handled anyway? Well, the problem with this problem being sent as an internal server error is that it's not originating from our side. The error of bad JSON format is caused by bad JSON data, something like a trailing comma in a JSON object.
You see, that error is thrown because of a client mistake. The error is triggered by something from the client side. We want the client to know that they did something wrong. We don't want the client to get furious at us because of a problem they are responsible for, that's what happens when we respond with status code 500 for all errors. This error is a special one, caused by a bad input format from the client. We want to send status code 400 instead.
The error caused by bad JSON format is thrown by the body parser but we can't put the body parser in a try-catch block and do what we want with the error. We will let the body parser forward the error to the global error handler then we handle it there.
We know it is a SyntaxError
, that's what we will be looking for. We also know that the message will say something about JSON. We use the type of the error and the error message to narrow down our action as done below:
const handleServerErrors = (
err:Error, req: Request, res: Response, next: NextFunction) =>{
if(err){
if (err instanceof SyntaxError){
if(/JSON/i.test(err.message)){
res.status(400).json("Bad JSON format")
} else{
res.status(500).json(err.message)
}
console.log(err.message)
} else{
res.status(500).json('Unexpected server error.')
console.log(`Name ${err.name},
Message:${err.message}`)
console.log(`Error Stack \n ${err.stack}`)
}
}
}
Now we pass the above error handler to the express app as the last middleware in the system. If the client sends data in bad JSON format, we will respond with status code 400 and a message informing them about the problem in the response body.
Top comments (0)