diff --git a/src/api/middlewares/ErrorHandler.ts b/src/api/middlewares/ErrorHandler.ts
index 052f2a3a..19d9203f 100644
--- a/src/api/middlewares/ErrorHandler.ts
+++ b/src/api/middlewares/ErrorHandler.ts
@@ -18,12 +18,24 @@
import { NextFunction, Request, Response } from "express";
import { HTTPError } from "lambert-server/HTTPError";
-import { ApiError, FieldError } from "@spacebar/util";
+import { ApiError, FieldError, FieldErrors } from "@spacebar/util";
+import { StringLengthOutOfBoundsException } from "@spacebar/extensions";
const EntityNotFoundErrorRegex = /"(\w+)"/;
export function ErrorHandler(error: Error & { type?: string }, req: Request, res: Response, next: NextFunction) {
if (!error) return next();
+ // Convert custom generic exception classes to spacebar errors
+ if (error instanceof StringLengthOutOfBoundsException)
+ error = FieldErrors({
+ [error.key]: {
+ code: "BASE_TYPE_BAD_LENGTH",
+ message: req.t("common:field.BASE_TYPE_BAD_LENGTH", {
+ length: `${error.min} - ${error.max}`,
+ }),
+ },
+ });
+
try {
let code = 400;
let httpcode = code;
diff --git a/src/extensions/String.ts b/src/extensions/String.ts
index fb34600f..96174244 100644
--- a/src/extensions/String.ts
+++ b/src/extensions/String.ts
@@ -16,10 +16,8 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-import { Request } from "express";
import { SPECIAL_CHAR } from "@spacebar/util/util/Regex";
import { Random, ntob } from "@spacebar/extensions";
-import { FieldErrors } from "@spacebar/util/util/FieldError";
export function trimSpecial(str?: string): string {
if (!str) return "";
@@ -49,16 +47,13 @@ export function stringGlobToRegexp(str: string, flags?: string): RegExp {
}
// TODO: use exception type
-export function stringCheckLength(str: string, min: number, max: number, key: string, req: Request) {
+export function stringCheckLength(str: string, min: number, max: number, key: string) {
if (str.length < min || str.length > max) {
- throw FieldErrors({
- [key]: {
- code: "BASE_TYPE_BAD_LENGTH",
- // TODO: remove dependency on request (add generic field?)
- message: req.t("common:field.BASE_TYPE_BAD_LENGTH", {
- length: `${min} - ${max}`,
- }),
- },
+ throw new StringLengthOutOfBoundsException({
+ key,
+ min,
+ max,
+ value: str,
});
}
}
@@ -66,3 +61,15 @@ export function stringCheckLength(str: string, min: number, max: number, key: st
export function generateCode() {
return ntob(Date.now() + Random.nextInt(0, 10000));
}
+
+export class StringLengthOutOfBoundsException extends RangeError {
+ min: number;
+ max: number;
+ key: string;
+ value: string;
+
+ constructor(opts: { min: number; max: number; key: string; value: string }) {
+ super(`String ${opts.key} must be between ${opts.min} and ${opts.max} characters`);
+ Object.assign(this, opts);
+ }
+}
|