feat: implement error handling and validation middleware, enhance result handling
Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
53
apps/backend/src/lib/http/problem-mapper.ts
Normal file
53
apps/backend/src/lib/http/problem-mapper.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { AppError } from '@/lib/errors'
|
||||
import type { ProblemDetails } from './problem-details'
|
||||
|
||||
function statusFromError(error: AppError): ContentfulStatusCode {
|
||||
switch (error.type) {
|
||||
case 'validation':
|
||||
return 400
|
||||
case 'unauthorized':
|
||||
return 401
|
||||
case 'forbidden':
|
||||
return 403
|
||||
case 'not_found':
|
||||
return 404
|
||||
case 'conflict':
|
||||
return 409
|
||||
case 'unexpected':
|
||||
default:
|
||||
return 500
|
||||
}
|
||||
}
|
||||
|
||||
function titleFromStatus(status: ContentfulStatusCode): string {
|
||||
switch (status) {
|
||||
case 400:
|
||||
return 'Bad Request'
|
||||
case 401:
|
||||
return 'Unauthorized'
|
||||
case 403:
|
||||
return 'Forbidden'
|
||||
case 404:
|
||||
return 'Not Found'
|
||||
case 409:
|
||||
return 'Conflict'
|
||||
default:
|
||||
return 'Internal Server Error'
|
||||
}
|
||||
}
|
||||
|
||||
export function mapAppErrorToProblem(
|
||||
error: AppError,
|
||||
instance?: string
|
||||
): ProblemDetails {
|
||||
const status = statusFromError(error)
|
||||
|
||||
return {
|
||||
type: `https://api.myapp.dev/problems/${error.type}`,
|
||||
title: titleFromStatus(status),
|
||||
status,
|
||||
detail: status === 500 ? 'Internal server error' : error.message,
|
||||
instance
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user