Why does the createError
function not showing all the parameters? Based on the documentation, the parameters available are err: { cause, data, message, name, stack, statusCode, statusMessage, fatal }
I tried it in my API but it does not work. I don’t see the cause
parameter as a response. I only see the statusCode
, statusMessage
, message
, and stack
. Anyone have the same problem? I am open for suggestions.
Here is my example codes.
export default defineEventHandler(async (event) => {
try {
const body: IFormEntries = await readBody(event)
if (!body) {
return createError({ statusCode: 500, statusMessage: 'Something went wrong.', cause: 'Not Working' })
}
return 200
} catch (error) {
return createError({ statusCode: 500, statusMessage: 'Something went wrong.' })
}
})
All I want is to display the cause of the error.
>Solution :
You can create you own error response.
If you want the error response to be flexible and you have full control of the parameters. This is the workaround that for me is effective.
You can have any parameter that you want as long as you include the statusCode
and the statusMessage
in the response.
~/types/index.ts
export interface IResponse {
statusCode: number
statusMessage: string
cause?: any
}
~/server/utils/error-response.ts
import { H3Event } from 'h3'
import { IResponse } from '~/types'
const errorResponse = (event: H3Event, response: IResponse): IResponse => {
event.node.res.statusCode = response.statusCode
event.node.res.statusMessage = response.statusMessage
return {
statusCode: response.statusCode,
statusMessage: response.statusMessage,
cause: response.cause ? response.cause : null
}
}
export default errorResponse
Usage. This is inside your APIs. It’s not necessary to import the file inside the utils
folder since it will automatically import it.
export default defineEventHandler(async (event) => {
try {
const body: IFormEntries = await readBody(event)
if (!body) {
return errorResponse(event, { statusCode: 400, statusMessage: 'Custom Message', cause: 'Body is required' })
}
return 200
} catch (error) {
return errorResponse(event, { statusCode: 500, statusMessage: 'Something went wrong.' })
}
})
Hope that helps you.