Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log an error's message without stack trace in JavaScript?

I want to log that an error occurred without exiting from the program, so i enclose the code that might throw an error in a try-catch block like such

try
{
    let query = parseStatement(input); // might throw an error
    console.log(query);
}
catch (err)
{
    console.error(err); // logs the entire error with stack trace
}
finally
{
    this.prompt();
}

The output I would like to obtain is the error's message without the whole stack trace. Something along the lines of:

Error: Missing semicolon at the end of statement: <statement>

and not

Error: Missing semicolon at the end of statement: <statement>
    at error (/home/nic/dev/nodedb/src/errors.js:5:11)
    at Function.tokenize (/home/nic/dev/nodedb/src/tokens.js:53:13)
    at parseStatement (/home/nic/dev/nodedb/src/sql.js:35:24)
    at Shell.onData (/home/nic/dev/nodedb/src/shell.js:49:25)
    at ReadStream.emit (node:events:394:28)
    at addChunk (node:internal/streams/readable:312:12)
    at readableAddChunk (node:internal/streams/readable:287:9)
    at ReadStream.Readable.push (node:internal/streams/readable:226:10)
    at TTY.onStreamRead (node:internal/stream_base_commons:190:23)
like image 209
Nicholas Obert Avatar asked May 27 '26 01:05

Nicholas Obert


1 Answers

From the documentation:

The Error object has a .message property, so instead of printing the whole error, just

console.error(error.message);
like image 191
Nicholas Obert Avatar answered May 28 '26 14:05

Nicholas Obert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!