Last active
March 16, 2023 12:35
-
-
Save yokotak0527/8c98690a7d8af16060a4a6a05120ce47 to your computer and use it in GitHub Desktop.
Koa error handling middleware
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 type { Next } from 'koa' | |
import type { RouterContext } from '@koa/router' | |
export default async function errorHandling(context:RouterContext, next:Next) { | |
try { | |
await next() | |
} catch(err:any) { | |
context.type = 'application/json' | |
context.status = | |
err.status || | |
err.statusCode || | |
err.status_code || | |
(err.output && err.output.statusCode) || | |
(err.oauthError && err.oauthError.statusCode) || | |
500 | |
let details:{[k: string]: any} = {} | |
if (err.details) { | |
details = err.details | |
} else { | |
Object.entries(err).forEach(([key, value]) => { | |
if (key === 'message') return | |
details[key] = value | |
}) | |
} | |
const res:App.ErrorResponse = { | |
status: context.status, | |
message: err.message || '', | |
statusMessage: `${context.status} ${context.message}`, | |
details | |
} | |
context.app.emit('error', err) | |
console.error(err) | |
context.body = res | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment