Skip to content

Instantly share code, notes, and snippets.

@Deviad
Created August 4, 2020 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deviad/3b5f9421f791fc5ca790458a57c94e34 to your computer and use it in GitHub Desktop.
Save Deviad/3b5f9421f791fc5ca790458a57c94e34 to your computer and use it in GitHub Desktop.
Error handling in Koa
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