Created
June 15, 2020 18:52
-
-
Save garenyondem/37f7202a48e13171463e414638cfc94f to your computer and use it in GitHub Desktop.
Async handler, wrapers, error handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.errorHandler = (response, err) => { | |
const statusCode = err.status || 500; | |
response.status(statusCode).json({ | |
success: false, | |
error: err.message | |
}); | |
}; | |
exports.successHandler = (response, data) => { | |
response.json({ | |
success: true, | |
data | |
}); | |
}; | |
exports.asyncHandler = fn => { | |
return async function(request, response) { | |
try { | |
const data = await fn(request, response); | |
exports.successHandler(response, data); | |
} catch (err) { | |
exports.errorHandler(response, err); | |
} | |
}; | |
}; | |
exports.asyncNextHandler = fn => { | |
return async function(request, response, next) { | |
try { | |
await fn(request, response, next); | |
next(); | |
} catch (err) { | |
exports.errorHandler(response, err); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment