Skip to content

Commit 8fb4ccd

Browse files
authored
Merge pull request #74 from domwebber/master
Add Error Handling for JSON body parsing
2 parents e541281 + 33314c1 commit 8fb4ccd

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

index.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,11 @@ app.all('*', (req, res) => {
105105

106106
//If the Content-Type of the incoming body `is` JSON, it can be parsed and returned in the body
107107
if(req.is('application/json')){
108-
echo.json = JSON.parse(req.body)
108+
try {
109+
echo.json = JSON.parse(req.body)
110+
} catch (error) {
111+
console.warn("Invalid JSON Body received with Content-Type: application/json", error);
112+
}
109113
}
110114

111115
//If there's a JWT header, parse it and decode and put it in the response

tests.sh

+9
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,15 @@ else
155155
exit 1
156156
fi
157157

158+
REQUEST=$(curl -s -X POST -H "Content-Type: application/json" -d 'not-json' http://localhost:8080)
159+
if [ $(echo $REQUEST | jq -r '.json') == 'null' ]; then
160+
passed "JSON with Invalid Body test passed."
161+
else
162+
failed "JSON with Invalid Body test failed."
163+
echo $REQUEST | jq
164+
exit 1
165+
fi
166+
158167
message " Stop containers "
159168
docker stop http-echo-tests
160169
sleep 5

0 commit comments

Comments
 (0)