import ResponseFactory from './ResponseFactory.ts' import {Request} from '../Request.ts' export default class ErrorResponseFactory extends ResponseFactory { protected target_mode: 'json' | 'html' = 'html' constructor( public readonly error: Error, status: number = 500, output: 'json' | 'html' = 'html', ) { super() this.status(status) this.mode(output) } public mode(output: 'json' | 'html'): ErrorResponseFactory { this.target_mode = output return this } public async write(request: Request): Promise { request = await super.write(request) if ( this.output === 'json' ) { request.response.headers.set('Content-Type', 'application/json') request.response.body = this.build_json(this.error) } else if ( this.output === 'html' ) { request.response.headers.set('Content-Type', 'text/html') request.response.body = this.build_html(this.error) } return request } protected build_html(error: Error) { return ` Sorry, an unexpected error occurred while processing your request.

Name: ${error.name}
Message: ${error.message}
Stack trace:
    - ${error.stack ? error.stack.split(/\s+at\s+/).slice(1).join('
- ') : 'none'}
` } protected build_json(error: Error) { return JSON.stringify({ success: false, error: { name: error.name, message: error.message, stack: error.stack ? error.stack.split(/\s+at\s+/).slice(1) : [] } }) } }