1. 错误消息格式

前后端消息传递时,我们可以通过 json 的 errors 字段传递错误信息,一个比较好的格式范例为:

{
errors: {
global: ["网络错误"],
password: ["至少需要一个大写字母", "至少需要八位字符"]
}
}

errors 中,字段名代表出错位置(如果是输入框的话,对应错误要显示在框下面),内容为一个数组,每个字符串代表一个错误。

2. 处理函数

可以新建一个 composables 文件夹,以存储各个 components 中共用的逻辑,例如错误消息处理。这里在 composables 文件夹中新建一个 error.ts

import { ref, type Ref } from 'vue';

export interface ErrorFields {
global: string[];
[key: string]: string[];
} export function useErrorFields(fields: string[]) {
const errors: Ref<ErrorFields> = ref({ global: [], ...fields.reduce((acc, field) => ({ ...acc, [field]: [] }), {}) });
const clearErrors = () => {
for (const field in errors.value) {
errors.value[field] = [];
}
};
const hasErrors = (field?: string) => {
if (field) {
return errors.value[field].length > 0;
}
return Object.values(errors.value).some((field) => field.length > 0);
};
const addError = (field: string, message: string) => {
if (field === '') {
field = 'global';
}
const array = errors.value[field];
if (!array.includes(message)) {
array.push(message);
}
return array;
};
const removeError = (field: string, message?: string) => {
if (field === '') {
field = 'global';
}
if (message) {
errors.value[field] = errors.value[field].filter((m) => m !== message);
} else {
errors.value[field] = [];
}
};
return { errors, clearErrors, hasErrors, addError, removeError };
}

这里我们就定义了错误类及其处理函数。

3. 组件中的使用

定义的 useErrorFields 工具可以在 component 中这样使用:

<script setup lang="ts">
import axios from 'axios';
import { computed, onMounted, ref, type Ref } from 'vue';
import { useErrorFields } from '@/composables/error'; const { errors, clearErrors, addError, hasErrors } = useErrorFields(['username', 'password']); const username = ref(''); function onSubmit() {
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
});
api.get("/user/register")
.catch((error) => {
if (error.response && error.response.data && error.response.data.errors) {
errors.value = { ...errors.value, ...error.response.data.errors };
} else if (error.response) {
addError('', '未知错误');
} else {
addError('', '网络错误');
}
})
}
</script> <template>
<div
v-if="hasErrors('global')"
class="mb-5 rounded-md border-0 shadow-sm ring-1 ring-inset ring-gray-300 dark:ring-gray-500 px-4 py-2"
>
<div class="flex text-red-700 dark:text-rose-400 space-x-2 mb-2">
<p class="text-lg font-semibold">错误</p>
</div>
<ul class="flex flex-col font-medium tracking-wide text-sm list-disc pl-6">
<li v-for="e in errors.global" v-html="e" />
</ul>
</div>
<form>
<div>
<label for="username" class="block text-sm font-medium leading-6">
用户名
<span class="text-red-700">*</span>
</label>
<div class="mt-2">
<input
v-model="username"
@focus="clearErrors"
id="username"
name="username"
type="text"
autocomplete="username"
required
class="block w-full rounded-md border-0 py-1.5 px-3 shadow-sm ring-1 ring-inset focus:ring-2 focus:ring-inset focus:ring-indigo-600 focus:outline-none sm:text-sm sm:leading-6 dark:bg-white/10 dark:ring-white/20"
:class="{ 'ring-red-500': hasErrors('username'), 'ring-gray-300': !hasErrors('username') }"
/>
</div>
<ul class="flex flex-col font-medium tracking-wide text-red-500 text-xs mt-1 ml-1">
<li v-for="e in errors.username" v-html="e" />
</ul>
</div>
<div>
<button
type="submit"
class="flex w-full justify-center rounded-md px-3 py-1.5 text-sm font-semibold leading-6 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 text-white shadow-sm hover:bg-indigo-500"
:class="{
'cursor-default pointer-events-none': hasErrors() || processing,
'bg-gray-400': hasErrors(),
'bg-indigo-600': !hasErrors(),
}"
>
注册
</button>
</div>
</form>
</template>

接下来,我们一步步解析以上代码。

3.1 根据后端响应更新错误状态

我们首先使用 useErrorFields 定义了一个错误状态类:

const { errors, clearErrors, addError, hasErrors } = useErrorFields(['username', 'password']);

这时候,错误状态 errors 中可访问三个字段,并将绑定到页面的不同位置:

global: 全局错误 / 无具体位置的错误 => 显示在表格顶端的单独框中

username: 用户名上的错误 => 显示在 username 输入框下方

password: 密码上的错误 => 显示在 password 输入框下方

接下来,我们需要定义提交函数,例如这里使用 axios 进行后端访问,后端地址用环境变量提供:

function onSubmit() {
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
});
api.get("/user/register")
.catch((error) => {
if (error.response && error.response.data && error.response.data.errors) {
errors.value = { ...errors.value, ...error.response.data.errors };
} else if (error.response) {
addError('', '未知错误');
} else {
addError('', '网络错误');
}
})
}

这样,后端返回错误信息时,错误状态会被自动更新。如果出现了网络错误或其他错误,addError类会在 global 字段上增加错误 (使用空字符串为第一个参数,默认添加到 global 字段)。

接下来,将错误状态绑定到页面。

3.2 绑定到输入框

<input
v-model="username"
@focus="clearErrors"
id="username"
name="username"
type="text"
autocomplete="username"
required
class="block w-full rounded-md border-0 py-1.5 px-3 shadow-sm ring-1 ring-inset focus:ring-2 focus:ring-inset focus:ring-indigo-600 focus:outline-none sm:text-sm sm:leading-6 dark:bg-white/10 dark:ring-white/20"
:class="{ 'ring-red-500': hasErrors('username'), 'ring-gray-300': !hasErrors('username') }"
/>

这里主要使用了两个个函数:

clearErrors: 当重新开始进行输入时,清除错误状态中的全部错误。

hasErrors: 当对应位置出现错误时,将输入框边框颜色变为红色。

将错误状态显示在输入框下:

<div>
<label for="username" class="block text-sm font-medium leading-6">
用户名
<span class="text-red-700">*</span>
</label>
<div class="mt-2">
<input
...
/>
</div>
<ul class="flex flex-col font-medium tracking-wide text-red-500 text-xs mt-1 ml-1">
<li v-for="e in errors.username" v-html="e" />
</ul>
</div>

这里我们使用 <li> 标签,使用 errors.username 将对应位置的错误消息依次显示在输入框下。

3.4 全局消息显示在表格顶端

<div
v-if="hasErrors('global')"
class="mb-5 rounded-md border-0 shadow-sm ring-1 ring-inset ring-gray-300 dark:ring-gray-500 px-4 py-2"
>
<div class="flex text-red-700 dark:text-rose-400 space-x-2 mb-2">
<p class="text-lg font-semibold">错误</p>
</div>
<ul class="flex flex-col font-medium tracking-wide text-sm list-disc pl-6">
<li v-for="e in errors.global" v-html="e" />
</ul>
</div>
<form>
...
</form>

这里使用 hasErrors('global') 来检测是否有全局错误,并在输入表顶端显示。

3.5 提交按钮在有错误时不允许点击

<button
type="submit"
class="flex w-full justify-center rounded-md px-3 py-1.5 text-sm font-semibold leading-6 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 text-white shadow-sm hover:bg-indigo-500"
:class="{
'cursor-default pointer-events-none': hasErrors(),
'bg-gray-400': hasErrors(),
'bg-indigo-600': !hasErrors(),
}"
>
注册
</button>

这里使用 hasErrors() 来检测错误状态类中是否有任何错误,并据此启用或禁用按钮。

4. 完整案例

如果你需要一个完整案例,这里有:错误状态处理在用户注册场景的案例,前端开源,详见:Github,你也可以访问 Githubstar.pro 来查看网页的效果(一个 Github 互赞平台,前端按本文方式进行错误处理)。

感谢阅读,如果本文对你有帮助,可以订阅我的博客,我将继续分享前后端全栈开发的相关实用经验。祝你开发愉快

Vue 3 后端错误消息处理范例的更多相关文章

  1. ASP.NET WebApi+Vue前后端分离之允许启用跨域请求

    前言: 这段时间接手了一个新需求,将一个ASP.NET MVC项目改成前后端分离项目.前端使用Vue,后端则是使用ASP.NET WebApi.在搭建完成前后端框架后,进行接口测试时发现了一个前后端分 ...

  2. Vue之前后端交互

    Vue之前后端交互 一.前后端交互模式 接口调用方式 原生ajax 基于jQuery的ajax fetch axios 异步 JavaScript的执行环境是「单线程」 所谓单线程,是指JS引擎中负责 ...

  3. 三、vue前后端交互(轻松入门vue)

    轻松入门vue系列 Vue前后端交互 六.Vue前后端交互 1. 前后端交互模式 2. Promise的相关概念和用法 Promise基本用法 then参数中的函数返回值 基于Promise处理多个A ...

  4. vue根据后端菜单自动生成路由(动态路由)

    vue根据后端菜单自动生成路由(动态路由) router.js import Vue from 'vue' import Router from 'vue-router' import store f ...

  5. 解决Django+Vue前后端分离的跨域问题及关闭csrf验证

      前后端分离难免要接触到跨域问题,跨域的相关知识请参:跨域问题,解决之道   在Django和Vue前后端分离的时候也会遇到跨域的问题,因为刚刚接触Django还不太了解,今天花了好长的时间,查阅了 ...

  6. Flask + vue 前后端分离的 二手书App

    一个Flask + vue 前后端分离的 二手书App 效果展示: https://blog.csdn.net/qq_42239520/article/details/88534955 所用技术清单 ...

  7. 喜大普奔,两个开源的 Spring Boot + Vue 前后端分离项目可以在线体验了

    折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...

  8. 基于Spring Boot+Spring Security+JWT+Vue前后端分离的开源项目

    一.前言 最近整合Spring Boot+Spring Security+JWT+Vue 完成了一套前后端分离的基础项目,这里把它开源出来分享给有需要的小伙伴们 功能很简单,单点登录,前后端动态权限配 ...

  9. 两个开源的 Spring Boot + Vue 前后端分离项目

    折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...

  10. beego-vue URL重定向(beego和vue前后端分离开发,beego承载vue前端分离页面部署)

    具体过程就不说,是搞这个的自然会动,只把关键代码贴出来. beego和vue前后端分离开发,beego承载vue前端分离页面部署 // landv.cnblogs.com //没有授权转载我的内容,再 ...

随机推荐

  1. docker 修改运行容器环境变量,如何修改容器中的环境变量env使长期有效

    @ 目录 前言 第一步:查看Docker Root目录 第二步:查到容器的长id(container id) 第三步:停止容器 第四步:编辑修改环境变量env 第五步:重载服务的配置文件 第六步:重启 ...

  2. NumPy 随机数据分布与 Seaborn 可视化详解

    随机数据分布 什么是数据分布? 数据分布是指数据集中所有可能值出现的频率,并用概率来表示.它描述了数据取值的可能性. 在统计学和数据科学中,数据分布是分析数据的重要基础. NumPy 中的随机分布 N ...

  3. SASS 运算 (Operations)符的基本使用

    ​ sass 运算符虽然没有像那些编程语言那么强大,但为了更灵活的输出css,也增强了一些运算符的功能,例如赋值运算符.等号操作符.比较运算符.逻辑运算符.字符串运算符...等等,接下来就来详细介绍下 ...

  4. FFmpeg中的常见结构体

    代码基于FFmpeg5.0.1 目录 FFFormatContext AVFormatContext AVIOContext FFIOContext URLContext URLProtocol AV ...

  5. .NET Core应用程序每次启动后使用string.GetHashCode()方法获取到的哈希值(hash)不相同

    前言 如标题所述,在ASP.NET Core应用程序中,使用string.GetHashCode()方法去获取字符串的哈希值,但每次重启这个ASP.NET Core应用程序之后,同样的字符串的哈希值( ...

  6. 容器化部署wordpress个人博客系统lnmp环境[自定义网络]

    容器化部署个人博客系统lnmp环境 #告警: WARNING: IPv4 forwarding is disabled. Networking will not work. 96c083a8b5811 ...

  7. 探索Semantic Plugins:开启大模型的技能之门

    前言 在之前的章节中我们或多或少的已经接触到了 Semantic Kernel 的 Plugins,本章我们讲详细介绍如何使用插件. Semantic Kernel 的一大特点是拥有强大的插件,通过结 ...

  8. Qt-ui的简单使用,常用控件(2)

    1  简介 本文主要介绍Qt ui界面的简单使用,介绍一些常用的控件. 参考视频:https://www.bilibili.com/video/BV1XW411x7NU?p=22 2  常用控件 常用 ...

  9. 京东web端h5st—4.7逆向分析

    声明 本文章中所有内容仅供学习交流,抓包内容.敏感网址.数据接口均已做脱敏处理,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除! 目标网站 aHR0cHM6 ...

  10. CSP-S2023 题解

    CSP-S 2023 题解 密码锁 发现总状态数只有 \(10^5\) 个,枚举 \(O(n)\) 暴力判断即可,复杂度 \(O(10^5 n)\). 或者每一个状态只对应了 \(81\) 个状态,枚 ...