Skip to content

Instantly share code, notes, and snippets.

@yokotak0527
Last active March 16, 2023 12:35
Show Gist options
  • Save yokotak0527/8c98690a7d8af16060a4a6a05120ce47 to your computer and use it in GitHub Desktop.
Save yokotak0527/8c98690a7d8af16060a4a6a05120ce47 to your computer and use it in GitHub Desktop.
Koa error handling middleware
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