flow-typer-js
Version:
Declarative static and runtime type checking with Flow
69 lines (61 loc) • 1.78 kB
JavaScript
//
import { getType } from './utils.js'
export class TypeValidatorError extends Error {
expectedType
valueType
value
typeScope
sourceFile
constructor (
message ,
expectedType ,
valueType ,
value ,
typeName = '',
typeScope = '',
) {
const errMessage = message ||
`invalid "${valueType}" value type; ${typeName || expectedType} type expected`
super(errMessage)
this.expectedType = expectedType
this.valueType = valueType
this.value = value
this.typeScope = typeScope || ''
this.sourceFile = this.getSourceFile()
this.message = `${errMessage}\n${this.getErrorInfo()}`
if (Error.captureStackTrace) {
Error.captureStackTrace(this, TypeValidatorError)
}
}
getSourceFile () {
const fileNames = this.stack.match(/(\/[\w_\-.]+)+(\.\w+:\d+:\d+)/g) || []
return fileNames.find(fileName => fileName.indexOf('/flow-typer-js/dist/') === -1) || ''
}
getErrorInfo () {
return `
file ${this.sourceFile}
scope ${this.typeScope}
expected ${this.expectedType.replace(/\n/g, '')}
type ${this.valueType}
value ${this.value}
`
}
}
TypeValidatorError.prototype.name = 'TypeValidatorError'
export const validatorError = (
typeFn ,
value ,
scope ,
message ,
expectedType ,
valueType
) => {
return new TypeValidatorError(
message,
expectedType || getType(typeFn),
valueType || typeof value,
typeof value === 'string' ? JSON.stringify(value) : '',
typeFn.name,
scope
)
}