1
Fork 0
mirror of https://github.com/Steffo99/festa.git synced 2024-10-16 15:07:27 +00:00
festa/utils/interrupt.ts

33 lines
792 B
TypeScript
Raw Normal View History

2022-05-31 03:03:48 +00:00
import { NextApiResponse } from "next"
/**
* Pseudo-decorator which intercepts thrown {@link Interrupt}s and turns them into HTTP responses.
*/
export async function handleInterrupts(res: NextApiResponse, f: () => Promise<void>) {
try {
return await f()
}
catch(e) {
if(e instanceof Interrupt) {
return res.status(e.status).json(e.response)
}
2022-06-03 01:55:02 +00:00
else {
console.error(e)
}
2022-05-31 03:03:48 +00:00
}
}
/**
* Error which interrupts the regular flow of a function to return a specific HTTP response.
*
* Caught by {@link interruptHandler}.
*/
export class Interrupt<R extends {}> {
status: number
response: R
constructor(status: number, response: R) {
this.status = status
this.response = response
}
}