From 5fa73a1f17f34af26b93c2b232e2c2cf386a04b5 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 27 May 2024 11:03:12 -0700 Subject: [PATCH] Added documentation for error handling --- README.md | 37 ++++++++++++++++++++++++++++++- Server/middleware/handleErrors.js | 9 +++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5440f0e7d..a8e1b1f32 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,8 @@ BlueWave uptime monitoring application - POST [/api/v1/monitors](#post-monitors) - POST [/api/v1/monitors/delete/{monitorId}](#post-monitors-del-id) - POST [/api/v1/monitors/edit/{monitorId}](#post-monitors-edit-id) -5. [Contributors](#contributors) +5. [Error Handling](#error-handling) +6. [Contributors](#contributors) --- @@ -544,6 +545,40 @@ curl --request POST \ --- +### Error handling {#error-handling} + +Errors are returned in a standard format: + +`{"success": false, "msg": "No token provided"}` + +Errors are handled by error handling middleware and should be thrown with the following parameters + +| Name | Type | Default | Notes | +| ------- | --------- | ---------------------- | ------------------------------------ | +| status | `integer` | 500 | Standard HTTP codes | +| message | `string` | "Something went wrong" | An error message | +| service | `string` | "Unknown Service" | Name of service that threw the error | + +Example: + +``` +const myRoute = async(req, res, next) => { + try{ + const result = myRiskyOperationHere(); + } + catch(error){ + error.status = 404 + error.message = "Resource not found" + error.service = service name + next(error) + return; + } +} + +``` + +Errors should not be handled at the controller level and should be left to the middleware to handle. + ## Contributors diff --git a/Server/middleware/handleErrors.js b/Server/middleware/handleErrors.js index 2febc6b31..78764c1e1 100644 --- a/Server/middleware/handleErrors.js +++ b/Server/middleware/handleErrors.js @@ -1,9 +1,12 @@ const logger = require("../utils/logger"); const handleErrors = (error, req, res, next) => { - error.status = error.status ? error.status : 500; - logger.error(error.message, { service: error.service }); - res.status(error.status).json({ success: false, msg: error.message }); + const status = error.status || 500; + const message = error.message || "Something went wrong"; + const service = error.errorService || "Unknown service"; + + logger.error(error.message, { service: service }); + res.status(status).json({ success: false, msg: message }); }; module.exports = { handleErrors };