Re-throwing exception in NodeJS and not losing stack trace

后端 未结 4 1243
一向
一向 2021-01-31 01:46

How can I rethrow an error or exception in nodejs/javascript and include a custom message.

I have the following code

var json = JSON.parse(result);
         


        
4条回答
  •  心在旅途
    2021-01-31 02:33

    If all you want to do is change the message, you can just change the message:

    try {
      throw new Error("Original Error");
    } catch(err) {
      err.message = "Here is some context -- " + err.message;
      throw err;
    }

    UPDATE:

    If the message property is readonly, you can create a new object using the original error as the prototype and assigning a new message:

    try {  // line 12
      document.querySelectorAll("div:foo");  // Throws a DOMException (invalid selector)
    } catch(err) {
      let message = "Here is some context -- " + err.message;
      let e = Object.create( err, { message: { value: message } } );
      throw e;  // line 17
    }

    Unfortunately, the logged message for an Exception is just "Uncaught exception" without the message that came with the Exception, so it might be helpful to create an Error and give it the same stack so the logged message will include the error message:

    try {  // line 12
      document.querySelectorAll("div:foo");  // Throws a DOMException (invalid selector)
    } catch(err) {
      e = new Error( "Here is some context -- " + err.message );
      e.stack = err.stack;
      throw e;  // line 17
    }

    Since the snippet output shows the line number of the re-throw, this confirms that the stack is preserved:

    try {  // line 12
      try {  // line 13
        document.querySelectorAll("div:foo");  // Throws a DOMException (invalid selector)
      } catch(err) {
        console.log( "Stack starts with message: ", err.stack.split("\n")[0] );
        console.log( "Inner catch from:", err.stack.split("\n")[1] );
        e = new Error( "Here is some context -- " + err.message );  // line 18
        console.log( "New error from:", e.stack.split("\n")[1] );
        e.stack = err.stack;
        throw e;  // line 21
      }
    } catch(err) {
      console.log( "Outer catch from:", err.stack.split("\n")[1] );
      throw err;  // line 25
    }

提交回复
热议问题