@dvsa/appdev-api-common
Version:
Utils library for common API functionality
43 lines (42 loc) • 1.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationError = void 0;
const http_status_codes_1 = require("../api/http-status-codes");
class ValidationError extends Error {
statusCode;
details;
constructor(statusCode = http_status_codes_1.HttpStatus.BAD_REQUEST, message = "Validation failed", details = null) {
super(message);
this.statusCode = statusCode;
this.details = details;
this.name = "ValidationError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ValidationError);
}
}
toJSON() {
return {
error: {
name: this.name,
message: this.message,
details: this.unwrapErrorDetails(this.details),
statusCode: this.statusCode,
},
};
}
unwrapErrorDetails = (details) => {
if (Array.isArray(details)) {
return details.map((error) => {
if (error &&
typeof error === "object" &&
"keyword" in error &&
error.keyword === "enum") {
return `${error.instancePath.replace("/", "")} ${error.message}: ${error.params?.allowedValues.join(", ")}`;
}
return error?.message || error;
});
}
return details;
};
}
exports.ValidationError = ValidationError;