【发布时间】:2022-01-04 18:51:48
【问题描述】:
我正在实现一个云功能,用于使用唯一的用户名和密码进行注册。
为了抛出异常,我之前做了以下操作:
signUpValidation.js
if (!validateUsername(username)) {
throw new functions.https.HttpsError(
"invalid-argument",
"Invalid username.",
{
status: "error",
code: "auth/invalid-username",
message: "Username must be between 3 and 30 characters, including numbers, letters, hyphens, periods, or underscores.",
}
);
}
signUp.function.js
try {
await validateSignUpData(
username,
email,
password,
repeatPassword,
name,
birthday,
clientIp
);
} catch(err) {
if (err instanceof functions.https.HttpsError) {
throw err;
}
// An unknown error has occurred
console.error(err);
throw new functions.https.HttpsError(
"unknown",
"Unexpected error.",
{
status: "error",
code: err.code ?? "unknown",
message: err.message ?? "The registration request could not be processed. Please, try again later."
}
);
}
但是,我真的不喜欢这种在 signUpValidation 模块中抛出异常的方式......对我来说,抛出“AuthErrors”而不是“HttpsErrors”更有意义。
因此,由于似乎无法扩展默认的 Firebase 错误,我决定创建自己的 util/authErrors 模块:
class AuthError extends Error {
constructor(code, message) {
super(message);
this.code = code;
this.name = "AuthError";
}
}
const authErrors = Object.freeze({
usernameAlreadyExists(message = "The username is already in use by an existing account") {
return new AuthError('auth/email-already-exists', message);
}
... more errors
});
module.exports = authErrors;
如您所见,我为每种错误类型创建了自定义错误和一些工厂函数。然后,在我的 signUpValidation.js 中,我只是这样做:
if (!(await isUsernameUnique(username))) {
throw authErrors.usernameAlreadyExists();
}
是否可以扩展 FirebaseError?如果不是,为什么?
以这种方式工作以在 Cloud Functions 中引发自定义异常是否被认为是一种不好的做法?我的意思是,我应该只抛出 HttpsErrors 吗?
【问题讨论】:
标签: javascript node.js firebase error-handling google-cloud-functions