daton/lib/src/http/response/ErrorResponseFactory.ts

51 lines
1.5 KiB
TypeScript
Raw Normal View History

import ResponseFactory from "./ResponseFactory.ts";
import {Request} from "../Request.ts";
export default class ErrorResponseFactory extends ResponseFactory {
constructor(
public readonly error: Error,
public readonly output: 'json' | 'html' = 'html',
public readonly status: number = 500,
) {
super()
}
public async write(request: Request): Promise<Request> {
request.response.status = this.status
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) : []
}
})
}
}