You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.6 KiB
55 lines
1.6 KiB
import ResponseFactory from './ResponseFactory.ts'
|
|
import {Request} from '../Request.ts'
|
|
import * as api from '../../support/api.ts'
|
|
import {HTTPStatus} from '../../const/http.ts'
|
|
|
|
export default class ErrorResponseFactory extends ResponseFactory {
|
|
protected target_mode: 'json' | 'html' = 'html'
|
|
|
|
constructor(
|
|
public readonly error: Error,
|
|
status: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
|
|
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> {
|
|
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 `
|
|
<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(api.error(error))
|
|
}
|
|
}
|