otto/type_error.go
Conrad Pankoff 67dbb5d65b fix: mishandling of message parameter in runtime.newErrorObject
runtime.newErrorObject is used to implement the Error constructor, and as such
it takes input from JavaScript via calls like `new Error('xxx')`. The actual
underlying error information is stored in an ottoError object, which is
constructed using newError. newError takes a couple of mandatory arguments,
then treats the remaining parameters (collected as `in ...interface{}`) as a
printf-style format string and parameter list, which it uses to populate the
message field of the returned ottoError object. newErrorObject was passing the
message parameter from the Error function exposed to JavaScript directly
through to newError as the first optional parameter, which led to it being
treated as a format string, which resulted in any code like `throw new
Error('%s')` behaving incorrectly, with the resultant error having a message
like "%!s(MISSING)".

This change fixes this behaviour in the least intrusive way I could find, and
adds some tests to make sure it doesn't come back.

The logic for newErrorObject and newErrorObjectError are very similar, so it
was tempting to try to merge them, but it appears they're used in somewhat
fragile ways with very little test coverage so I'll leave that as a problem
for another day.
2023-07-06 20:41:55 +10:00

59 lines
1.6 KiB
Go

package otto
func (rt *runtime) newErrorObject(name string, message Value, stackFramesToPop int) *object {
obj := rt.newClassObject(classErrorName)
if message.IsDefined() {
err := newError(rt, name, stackFramesToPop, "%s", message.string())
obj.defineProperty("message", err.messageValue(), 0o111, false)
obj.value = err
} else {
obj.value = newError(rt, name, stackFramesToPop)
}
obj.defineOwnProperty("stack", property{
value: propertyGetSet{
rt.newNativeFunction("get", "internal", 0, func(FunctionCall) Value {
return stringValue(obj.value.(ottoError).formatWithStack())
}),
&nilGetSetObject,
},
mode: modeConfigureMask & modeOnMask,
}, false)
return obj
}
func (rt *runtime) newErrorObjectError(err ottoError) *object {
obj := rt.newClassObject(classErrorName)
obj.defineProperty("message", err.messageValue(), 0o111, false)
obj.value = err
switch err.name {
case "EvalError":
obj.prototype = rt.global.EvalErrorPrototype
case "TypeError":
obj.prototype = rt.global.TypeErrorPrototype
case "RangeError":
obj.prototype = rt.global.RangeErrorPrototype
case "ReferenceError":
obj.prototype = rt.global.ReferenceErrorPrototype
case "SyntaxError":
obj.prototype = rt.global.SyntaxErrorPrototype
case "URIError":
obj.prototype = rt.global.URIErrorPrototype
default:
obj.prototype = rt.global.ErrorPrototype
}
obj.defineOwnProperty("stack", property{
value: propertyGetSet{
rt.newNativeFunction("get", "internal", 0, func(FunctionCall) Value {
return stringValue(obj.value.(ottoError).formatWithStack())
}),
&nilGetSetObject,
},
mode: modeConfigureMask & modeOnMask,
}, false)
return obj
}