ts类型检查

This commit is contained in:
yml
2026-05-04 09:43:38 +08:00
parent a914b7b828
commit 66261e56d1
23 changed files with 223 additions and 76 deletions
+41 -4
View File
@@ -1,7 +1,28 @@
// @ts-check
import { logError, logWarn } from './logger.js'
const RESPONSE_TIME_ZONE = 'Asia/Shanghai'
/**
* @typedef {{
* statusCode?: number
* errorCode?: string
* cause?: unknown
* context?: unknown
* [key: string]: unknown
* }} HttpErrorLike
*/
/**
* @typedef {{
* statusCode?: number
* errorCode?: string
* cause?: unknown
* context?: unknown
* }} CreateHttpErrorOptions
*/
export function buildSuccessPayload(data, msg = 'ok') {
return {
code: 0,
@@ -43,17 +64,33 @@ export function buildNotFoundPayload(req) {
}
}
export function createHttpError(message, { statusCode = 500, errorCode = '' } = {}) {
const error = new Error(message)
/**
* @param {string} message
* @param {CreateHttpErrorOptions} [options]
* @returns {Error & HttpErrorLike}
*/
export function createHttpError(message, options = {}) {
const { statusCode = 500, errorCode = '', cause, context } = options
const error = /** @type {Error & HttpErrorLike} */ (new Error(message))
error.statusCode = statusCode
error.errorCode = errorCode || defaultErrorCodeForStatus(statusCode)
if (typeof cause !== 'undefined') {
error.cause = cause
}
if (typeof context !== 'undefined') {
error.context = context
}
return error
}
function classifyRouteError(error) {
if (error && typeof error === 'object') {
const statusCode = Number(error.statusCode)
const errorCode = String(error.errorCode || '').trim()
const currentError = /** @type {HttpErrorLike} */ (error)
const statusCode = Number(currentError.statusCode)
const errorCode = String(currentError.errorCode || '').trim()
if (Number.isInteger(statusCode) && statusCode >= 400 && statusCode < 600) {
return {
+5 -2
View File
@@ -206,12 +206,15 @@ function normalizeLogValue(value) {
return JSON.parse(
JSON.stringify(value, (_key, current) => {
if (current instanceof Error) {
const currentError = /** @type {import('./http.js').HttpErrorLike} */ (
/** @type {unknown} */ (current)
)
return {
name: current.name,
message: current.message,
stack: current.stack,
statusCode: current.statusCode,
errorCode: current.errorCode,
statusCode: currentError.statusCode,
errorCode: currentError.errorCode,
}
}