Skip to content

Commit a574f7a

Browse files
committed
Minor Error handling refactor
- Make `Error::Message()` a proper `noexcept` method because it is called by `what()` - Mark the `_message` member of `Error` mutable instead of using a `const_cast`, this is what `mutable` is there for.
1 parent a9c08d1 commit a574f7a

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

napi-inl.h

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,12 +1198,15 @@ inline Error::Error() : Object(), _message(nullptr) {
11981198
inline Error::Error(napi_env env, napi_value value) : Object(env, value) {
11991199
}
12001200

1201-
inline std::string Error::Message() const {
1201+
inline const std::string& Error::Message() const NAPI_NOEXCEPT {
12021202
if (_message.size() == 0 && _env != nullptr) {
12031203
try {
1204-
const_cast<Error*>(this)->_message = (*this)["message"].As<String>();
1204+
_message = (*this)["message"].As<String>();
12051205
}
1206-
catch (const Error&) {
1206+
catch (...) {
1207+
// Catch all errors here, to include e.g. a std::bad_alloc from
1208+
// the std::string::operator=, because this is used by the
1209+
// Error::what() noexcept method.
12071210
}
12081211
}
12091212
return _message;

napi.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ namespace Napi {
449449
Error();
450450
Error(napi_env env, napi_value value);
451451

452-
std::string Message() const;
452+
const std::string& Message() const NAPI_NOEXCEPT;
453453
void ThrowAsJavaScriptException() const;
454454

455455
const char* what() const NAPI_NOEXCEPT override;
@@ -464,7 +464,7 @@ namespace Napi {
464464
create_error_fn create_error);
465465

466466
private:
467-
std::string _message;
467+
mutable std::string _message;
468468
};
469469

470470
class TypeError : public Error {

0 commit comments

Comments
 (0)