2020-07-30 03:55:17 +00:00
|
|
|
import ResponseFactory from './ResponseFactory.ts'
|
|
|
|
import {Request} from '../Request.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
|
|
|
|
|
|
|
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 `
|
|
|
|
<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) {
|
|
|
|
return JSON.stringify({
|
|
|
|
success: false,
|
|
|
|
error: {
|
|
|
|
name: error.name,
|
|
|
|
message: error.message,
|
|
|
|
stack: error.stack ? error.stack.split(/\s+at\s+/).slice(1) : []
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|