使用some 或者 every 方法遇到异常没有return

解决方法

使用for循环或者for of遍历

for (const file of filesArray) {try {formatBytes(file.size);} catch (e: any) {setErrorMessage(e.message);return;}}

问题复现

写了一个方法(formatBytes)将文件的大小自动转换成MBKB等,如果其中文件大小超过指定大小会抛出异常。想法是在遍历文件列表时如果超过指定大小,给出提示并且直接return

formatBytes方法

import { maxFileSize } from '@/config/fileType';export function formatBytes(bytes: number, decimals = 2) {const size = maxFileSize * 1024 * 1024;if (bytes > size) { throw new Error(`文件不能超过${maxFileSize}M`);}if (bytes === 0) return '0 Bytes';const k = 1024;const dm = decimals < 0 ? 0 : decimals;const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];const i = Math.floor(Math.log(bytes) / Math.log(k));return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;}

然而,在实际使用中,无论是使用someforEach还是every方法,都会在最后设上值。在遇到异常时,这几个方法并没有立即返回。

代码如下

// 文件改变时const handelFilesChange = (event: any) => {const filesArray: File[] = Array.from(event.target.files);filesArray.forEach(file => {try {formatBytes(file.size);} catch (e: any) {setErrorMessage(e.message);return;}});const map = filesArray.map(file => ({ id: uuid(), file }));setFiles(map);};

通过使用普通的for循环或for...of遍历,可以在捕获到异常时直接设置错误消息并立即返回,避免在异常情况下继续执行不必要的代码。