Implement Enum‑Like Error Codes in Vue with a Shared Utility Module
The article shows how to avoid hard‑coded status strings in Vue by defining a reusable errorCode module, importing it where needed, and mapping backend response codes to human‑readable messages with a default fallback, simplifying maintenance across the project.
Scenario
If a status value is needed in multiple places or a business flow requires several status values, using plain literals can lead to scattered definitions and difficult updates.
Implementation
Create a utils directory in the project and add errorCode.js with an exported object that maps status codes to descriptive messages, including a default entry.
export default {
'401': '认证失败,无法访问系统资源',
'403': '当前操作没有权限',
'404': '访问资源不存在',
'default': '系统未知错误,请反馈给管理员'
}Customize the error codes and the default message as needed.
Usage
In any file that needs to interpret a response code, import the module: import errorCode from '@/utils/errorCode' Then retrieve the appropriate message, falling back to a success code (200) or the default message when the code is not defined:
// 未设置状态码则默认成功状态
const code = res.data.code || 200;
// 获取错误信息
const message = errorCode[code] || res.data.msg || errorCode['default']The code comes from the backend; the lookup errorCode[code] returns the corresponding description. If the code is missing, the expression uses the response's own message or the predefined default: errorCode['default'] This returns the default error text "系统未知错误,请反馈给管理员".
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
