-
-
Save Deviad/3b5f9421f791fc5ca790458a57c94e34 to your computer and use it in GitHub Desktop.
Error handling in Koa
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
import { ExtendableContext } from 'koa'; | |
function buildErrorResponse(error: Error, ctx: ExtendableContext) { | |
let errors = []; | |
if (error instanceof Error) { | |
errors.push(error.message); | |
ctx.status = 500; | |
} | |
ctx.body = { | |
status: 'error', | |
message: errors, | |
}; | |
} | |
export const handleErrors = (fn: Function, ctx: ExtendableContext): any => { | |
try { | |
const result = fn(); | |
if (result instanceof Promise) { | |
return result | |
.then((x) => x) | |
.catch((error: Error) => { | |
buildErrorResponse(error, ctx); | |
}); | |
} | |
return result; | |
} catch (error) { | |
buildErrorResponse(error, ctx); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment