import ResponseFactory from './ResponseFactory.ts' import {Request} from '../Request.ts' import * as api from '../../support/api.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.target_mode === 'json' ) { request.response.headers.set('Content-Type', 'application/json') request.response.body = this.build_json(this.error) } else if ( this.target_mode === '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(api.error(error)) } }