Skip to content

Instantly share code, notes, and snippets.

@Deviad
Created Aug 4, 2020
Embed
What would you like to do?
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