(
status: HttpErrorStatus,
type: ProblemType,
title: string,
options: StreamingErrorOptions = {},
)
| 187 | } |
| 188 | |
| 189 | export function streamingProblemEvent( |
| 190 | status: HttpErrorStatus, |
| 191 | type: ProblemType, |
| 192 | title: string, |
| 193 | options: StreamingErrorOptions = {}, |
| 194 | ): StreamingProblemEvent { |
| 195 | const instance = options.instance ?? `urn:uuid:${randomUUID()}`; |
| 196 | const problem: ProblemDetails = { |
| 197 | type, |
| 198 | title, |
| 199 | status, |
| 200 | instance, |
| 201 | detail: options.detail ?? undefined, |
| 202 | }; |
| 203 | const event: StreamingProblemEvent = { type: 'error', problem }; |
| 204 | const validated = StreamingProblemEventSchema.safeParse(event); |
| 205 | if (!validated.success) { |
| 206 | log().error( |
| 207 | { |
| 208 | event: 'api.streaming.malformed-envelope', |
| 209 | issues: validated.error.issues, |
| 210 | body: event, |
| 211 | handler: options.handler, |
| 212 | originalStatus: status, |
| 213 | }, |
| 214 | 'streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback', |
| 215 | ); |
| 216 | const fallbackStatus = 500 as const; |
| 217 | apiErrorCounter().add(1, { |
| 218 | type: 'urn:ok:error:internal-server-error', |
| 219 | ...(options.handler ? { handler: options.handler } : {}), |
| 220 | }); |
| 221 | return { |
| 222 | type: 'error', |
| 223 | problem: { |
| 224 | type: 'urn:ok:error:internal-server-error', |
| 225 | title: 'Internal server error.', |
| 226 | status: fallbackStatus, |
| 227 | instance, |
| 228 | }, |
| 229 | }; |
| 230 | } |
| 231 | |
| 232 | apiErrorCounter().add(1, { |
| 233 | type, |
| 234 | ...(options.handler ? { handler: options.handler } : {}), |
| 235 | }); |
| 236 | |
| 237 | const logLevel = status >= 500 ? 'error' : 'warn'; |
| 238 | log()[logLevel]( |
| 239 | { |
| 240 | event: 'api.streaming.error', |
| 241 | instance, |
| 242 | type, |
| 243 | status, |
| 244 | handler: options.handler, |
| 245 | detail: options.detail, |
| 246 | err: options.cause, |
no test coverage detected