Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - How to catch an exception from the calling file?

I have the following Javascript code

main.js

'use-strict';
const assert = require('assert');
var r = require('./index.js');
async function fun() {
    try {
    r.start();
} catch (e) {console.log(e);}
}
fun();

index.js

'use-strict';
var assert = require('assert');
async function start() {
   
    assert.ok(1==0);
}

exports.start = start;

Now the exception thrown in index.js is NOT caught in main.js, why so ? Is there any way I can facilitate this ?

I have a series of functions in different files invoked from main.js and I don't want to put try/catch in all of them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you change main.js to this, hopefully the error will be caught as the function will wait for the promise to resolve, and throw the error in main.js.

main.js

'use-strict'
const assert = require('assert')
const r = require('./index.js')
const fun = async () => {
  try {
    // Wait for the promise to resolve
    await r.start()
  } catch (error) {
    console.log(error)
    throw new Error(`[main.js] - Error was thrown ${error}`)
  }
}
fun()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...