You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript自定义错误类修改消息未显示问题排查与解决

TypeScript自定义错误类消息不生效问题排查与解决

问题描述

在TypeScript中使用自定义错误类时,修改后的错误消息无法正确显示,仅能获取API返回的原始错误信息。相关代码如下:

CustomError基类

export class CustomError extends Error {
    cod:string;
    constructor(cod:string , message: string){
        super(message);
        this.cod = cod;
        Object.setPrototypeOf(this , new.target.prototype);

        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
}

CityNotFoundError继承类

import { CustomError } from "./CustomError";

export class CityNotFoundError extends CustomError {
    constructor(cod:string , message: string){
        const errMsg:string = message + " :The city you provided was not found,Please verify"
        super(cod,errMsg);
    }
}

错误处理函数

import { CityNotFoundError } from "../Errors/CityNotFoundError";
export function ErrorHandler(cod: string , message: string){
    switch(cod){
        case '404':
            const errMsg:string = message + " :The city you provided was not found,Please verify"
            return new CityNotFoundError(cod,errMsg);
    }
}

请求处理函数

app.get('/',async (req:Request,res:Response) =>{
    await fetch(`https://api.openweathermap.org/data/2.5/weather?q={location}&&appid={API_KEY}`).
    then(async(response) =>{ 
        const data = await response.json();
        console.log(data)
        res.json(data);
    }).
        catch(async(err) =>{
            const error = ErrorHandler(err.cod , err.message)!;
            console.error(error.stack);
            res.status(500).json({
                code: error.cod,
                message: error.message,
            });
        })
})

当前实际返回:

{ "cod": "404", "message": "city not found" }

期望返回:

{ "cod": "404", "message": "city not found :The city you provided was not found,Please verify" }

原因分析

  1. Fetch API错误处理逻辑错误:Fetch仅在网络故障或请求无法完成时才会触发catch块,HTTP 4xx/5xx这类状态码不会自动进入catch。当前代码中,当API返回404时,then块会正常执行并直接返回API的原始错误响应,根本没走到自定义错误处理的逻辑里。
  2. 重复拼接错误消息:即使catch块被触发,错误处理函数ErrorHandler已经拼接了一次消息,CityNotFoundError构造函数又会再拼接一次,最终消息会出现重复后缀,不符合预期。

修复方案

步骤1:修正Fetch的错误处理逻辑

在then块中先判断响应状态,若不是成功状态则抛出包含API错误信息的对象,让catch块能捕获到并处理:

app.get('/',async (req:Request,res:Response) =>{
    await fetch(`https://api.openweathermap.org/data/2.5/weather?q={location}&&appid={API_KEY}`)
    .then(async(response) =>{ 
        if (!response.ok) {
            // 解析API返回的错误信息并抛出
            const errorData = await response.json();
            throw errorData;
        }
        const data = await response.json();
        console.log(data)
        res.json(data);
    })
    .catch(async(err) =>{
        const error = ErrorHandler(err.cod , err.message)!;
        console.error(error.stack);
        res.status(Number(err.cod) || 500).json({
            code: error.cod,
            message: error.message,
        });
    })
})

步骤2:移除重复的消息拼接

选择在ErrorHandler或CityNotFoundError构造函数中只做一次消息拼接即可,比如修改CityNotFoundError构造函数:

import { CustomError } from "./CustomError";

export class CityNotFoundError extends CustomError {
    constructor(cod:string , message: string){
        // 由ErrorHandler负责拼接消息,子类直接传递
        super(cod, message);
    }
}

或者保留CityNotFoundError的拼接逻辑,修改ErrorHandler:

export function ErrorHandler(cod: string , message: string){
    switch(cod){
        case '404':
            // 直接传入原始消息,由子类完成拼接
            return new CityNotFoundError(cod, message);
    }
}

验证结果

修复后,当API返回404错误时,请求会进入catch块,通过自定义错误类生成带额外上下文的消息,最终返回符合预期的响应:

{ "cod": "404", "message": "city not found :The city you provided was not found,Please verify" }

同时console.error(error.stack)会打印包含自定义错误类调用栈的日志,确保额外上下文能被完整记录。


内容的提问来源于stack exchange,提问作者freedom_10107

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 23:58:21