52 lines
1.1 KiB
TypeScript
52 lines
1.1 KiB
TypeScript
/**
|
|
* Turns errors thrown while handling a request into `APIFailure` responses.
|
|
*
|
|
* @module
|
|
*/
|
|
|
|
import { Context, Next } from "@oak/oak";
|
|
|
|
import { APIErrorCode, APIFailure } from "../../shared/api.ts";
|
|
import { APIException } from "../lib/api-exception.ts";
|
|
|
|
/**
|
|
* Answers an {@link APIException} with its status and code, and anything else
|
|
* with a 500 `SERVER_ERROR`, logging both.
|
|
*/
|
|
export async function errorMiddleware(
|
|
ctx: Context,
|
|
next: Next,
|
|
): Promise<void> {
|
|
try {
|
|
await next();
|
|
} catch (err) {
|
|
if (err instanceof APIException) {
|
|
const responseBody: APIFailure = {
|
|
success: false,
|
|
error: {
|
|
code: err.code,
|
|
message: err.message,
|
|
},
|
|
};
|
|
|
|
ctx.response.status = err.status;
|
|
ctx.response.body = responseBody;
|
|
|
|
console.log(responseBody);
|
|
} else {
|
|
console.error(err);
|
|
|
|
const responseBody: APIFailure = {
|
|
success: false,
|
|
error: {
|
|
code: APIErrorCode.SERVER_ERROR,
|
|
message: "Unexpected server error",
|
|
},
|
|
};
|
|
|
|
ctx.response.status = 500;
|
|
ctx.response.body = responseBody;
|
|
}
|
|
}
|
|
}
|