2020-07-30 03:55:17 +00:00
|
|
|
import ResponseFactory from './ResponseFactory.ts'
|
|
|
|
import {Request} from '../Request.ts'
|
2020-07-30 04:18:38 +00:00
|
|
|
import * as api from '../../support/api.ts'
|
2020-07-30 03:01:20 +00:00
|
|
|
|
|
|
|
export default class ErrorResponseFactory extends ResponseFactory {
|
2020-07-30 03:55:17 +00:00
|
|
|
protected target_mode: 'json' | 'html' = 'html'
|
|
|
|
|
2020-07-30 03:01:20 +00:00
|
|
|
constructor(
|
|
|
|
public readonly error: Error,
|
2020-07-30 03:55:17 +00:00
|
|
|
status: number = 500,
|
|
|
|
output: 'json' | 'html' = 'html',
|
2020-07-30 03:01:20 +00:00
|
|
|
) {
|
|
|
|
super()
|
2020-07-30 03:55:17 +00:00
|
|
|
this.status(status)
|
|
|
|
this.mode(output)
|
|
|
|
}
|
|
|
|
|
|
|
|
public mode(output: 'json' | 'html'): ErrorResponseFactory {
|
|
|
|
this.target_mode = output
|
|
|
|
return this
|
2020-07-30 03:01:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async write(request: Request): Promise<Request> {
|
2020-07-30 03:55:17 +00:00
|
|
|
request = await super.write(request)
|
2020-07-30 03:01:20 +00:00
|
|
|
|
2020-07-30 04:18:38 +00:00
|
|
|
if ( this.target_mode === 'json' ) {
|
2020-07-30 03:01:20 +00:00
|
|
|
request.response.headers.set('Content-Type', 'application/json')
|
|
|
|
request.response.body = this.build_json(this.error)
|
2020-07-30 04:18:38 +00:00
|
|
|
} else if ( this.target_mode === 'html' ) {
|
2020-07-30 03:01:20 +00:00
|
|
|
request.response.headers.set('Content-Type', 'text/html')
|
|
|
|
request.response.body = this.build_html(this.error)
|
|
|
|
}
|
|
|
|
|
|
|
|
return request
|
|
|
|
}
|
|
|
|
|
|
|
|
protected build_html(error: Error) {
|
|
|
|
return `
|
|
|
|
<b>Sorry, an unexpected error occurred while processing your request.</b>
|
|
|
|
<br>
|
|
|
|
<pre><code>
|
|
|
|
Name: ${error.name}
|
|
|
|
Message: ${error.message}
|
|
|
|
Stack trace:
|
|
|
|
- ${error.stack ? error.stack.split(/\s+at\s+/).slice(1).join('<br> - ') : 'none'}
|
|
|
|
</code></pre>
|
|
|
|
`
|
|
|
|
}
|
|
|
|
|
|
|
|
protected build_json(error: Error) {
|
2020-07-30 04:18:38 +00:00
|
|
|
return JSON.stringify(api.error(error))
|
2020-07-30 03:01:20 +00:00
|
|
|
}
|
|
|
|
}
|