bunway
Version:
Express-style routing toolkit built natively for Bun.
67 lines • 2.19 kB
JavaScript
import { buildHttpErrorResponse, HttpError, isHttpError } from "../core/errors";
/** Create an error-handling middleware with optional logging and mapping. */
export function errorHandler(options = {}) {
const { logger, map } = options;
return async (ctx, next) => {
try {
await next();
return;
}
catch (err) {
let handledError = err;
if (map) {
try {
const mapped = map(err, ctx);
if (mapped) {
handledError = mapped;
}
}
catch (mapError) {
logger?.(mapError, ctx);
handledError = err;
}
}
if (handledError instanceof Response) {
return handledError;
}
let httpError;
if (isHttpError(handledError)) {
httpError = handledError;
}
else if (handledError instanceof Error) {
if (logger) {
try {
logger(handledError, ctx);
}
catch {
// ignore logger failures
}
}
httpError = new HttpError(500, "Internal Server Error", {
cause: handledError,
});
}
else {
if (logger) {
try {
logger(handledError, ctx);
}
catch {
// ignore logger failures
}
}
httpError = new HttpError(500, "Internal Server Error");
}
if (logger && httpError.status >= 500 && isHttpError(handledError)) {
try {
logger(handledError, ctx);
}
catch {
// ignore logger failures
}
}
return buildHttpErrorResponse(ctx, httpError);
}
};
}
//# sourceMappingURL=errorHandler.js.map