So I am working on a side project and I am trying to create my own personal utility library and I am making use of the ES6 class. This is what the class looks like currently.
class HttpUtils {
throwHttpError({ code, id, title, message, stack }) {
const toReturn = {
errors: [
{
id,
title,
error: message,
stack,
},
],
}
return {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
code,
data: JSON.stringify(toReturn),
}
}
wrapAsync(fn) {
return (req, res) =>
fn(req, res).catch((error) => {
return this.throwHttpError({
message: error.message,
title: error.name,
stack: error.stack,
code: error instanceof RequiredParameterError ||
error instanceof MessageBrokerError ||
error instanceof SendGridError
? 400
: 500 || error instanceof UnauthorizedError
? error.statusCode
: 401 || error instanceof DatabaseError
? error.statusCode
: 400,
})
})
}
}
The issue I am facing currently is that the wrapAsync
method doesn't work the way it is meant to work. This is how I implement the wrapAsync
method.
import { HttpUtils } from 'my-utils'
const http = new HttpUtils()
const someRandomFunc = ({ someDependency }) => {
return http.wrapAsync(async (httpRequest) => {
const { user } = httpRequest
const { ...details } = httpRequest.body
await someDependency({ user, ...details })
return http.apiResponse({
status: true,
message: 'Function completed',
data: null,
statusCode: 200
})
})
}
export default someRandomFunc
Anytime an error is thrown, I get this in my console.
(node:13444) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:536:11)
at ServerResponse.header (K:\moneyguard\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (K:\moneyguard\node_modules\express\lib\response.js:170:12)
at K:\moneyguard\api\express\/index.js:33:57
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13444) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either
I tried to console.log
the error that might have been thrown in the API, it is logged correctly and formatted correctly based on throwHttpError
, e.g
errors: [
{
title: RequiredParameterError,
error: Name cannot be null,
stack: ...some stack trace
}
]
But the wrapAsync
method doesn't behave properly, could it be as a result of the this
keyword or could I be missing something?
Thanks in advance.