Skip to content

Instantly share code, notes, and snippets.

@Lyokolux
Created October 6, 2022 12:42
Show Gist options
  • Save Lyokolux/a040d9d04bc89d1424ed898da5e6eba9 to your computer and use it in GitHub Desktop.
Save Lyokolux/a040d9d04bc89d1424ed898da5e6eba9 to your computer and use it in GitHub Desktop.
Error format implementation of the RFC 7807 for NodeJS HTTP environments
import type { CompatibilityEvent } from 'h3'
import HttpStatusCode from '~~/const/httpStatusCode'
import { APIErrorTitle } from './apiErrorTitle'
/** Format of the [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807) */
export type useAPIErrorOptions<T> = T & {
/** A URI that identifies the problem type.
* This specification encourages that, when dereferenced,
* it provide human-readable documentation for the problem type
*/
type?: string
/**
* Human-readable summary of the problem
*/
title?: APIErrorTitle
/**
* Redondant HTTP code with the one in header
*/
status: HttpStatusCode
/**
* A human-readable explanation specific to error. Ought to focus on helping the client correct the problem.
*/
detail?: string
/**
* a URI reference that identifies the specific occurrence of the problem.
* Default to the current route called
*/
instance?: string
}
/**
* Standard way to send an error to the client.
*
* @param event the object provided by an eventHandler of H3
* @param options fields of the [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807)
* @returns the modified event. Ready to be returned as response.
*/
export const useAPIError = <T>(event: CompatibilityEvent, options: useAPIErrorOptions<T>) => {
const { res } = event
// Modify the request status code in-place
res.statusCode = options.status
// Set the expected header
res.setHeader('Content-Type', 'application/problem+json')
if (!options.instance) {
options.instance = event.req.url
}
return options
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment