[Ethereum] How to catch error thrown by require in node.js

solidityweb3js

I have a solidity function with only one statement i.e., require(). My logic is if that function throws error then the data is invalid otherwise valid. But that error is not caught in err parameter of callback but instead express's error middleware is invoked. Although there is a way to specifically catch that error in middleware ( something like: app.use('/api', function(err, req, res, next(){ … }) }. But that would put the could in different file which i dont want. Is there any way to catch it.

//routes/user.js
router.get('/', function(req,res,next){
try{
myContract.verify(username, password, function(err,result){
if(!err){
res.render('error','user already exist');
}
});
}catch(e){
// Do something
}
});

//myContract.sol

contract mContract {

function verify(string memory _user, string memory _passwd) public view {
require(
      (keccak256(bytes(userMap[_user].user)) == keccak256(bytes(_user))) &&
      (keccak256(bytes(userMap[_user].passwd)) == keccak256(bytes(_passwd))),
      "Invalid"
);
}

I have used require() such that when the user/passwd does not match the require function throws error, which should be caught in err parameter of callback provided to contact method; otherwise it renders error page saying 'user already exist'. As of now when condition within require fails, the control flow does not go inside catch block but instead goes to error handler function defined in app.js. Although i can catch that error, using the example mentioned above, but then logic will be inside app.js.

Best Answer

Wrap the method invocation in a try/catch in your JS application to catch errors such as reverts thrown by solidity:

app.use('/api', function(err, req, res, next) {
    try {
      // add your smart contract function call here

      next()
    } catch(err) {
      // handle error here

      next(err)
    }
}) 
Related Topic