Outputing a json string and exit (like die() in php)


PHP situation: When a given endpoint of my API is reached, a json string is outputed for being consumed. I sent the proper headers, echo the string and exit the script using die(). I could do it more brutally just by doing die($json_string);

I was wondering if the same could be done using javascript. I know that throw new Error(json_string); would pretty much do it. But is that good practice? Would window.stop be of any use?

I expect questions such as: why you wanna do that? why don’t you do it in php? answer: for the sake of experimenting and learning.


When it’s a programmer error that causes the problem, it is good to have the program fail as quickly as possible so yes, in such cases it is a good practice.

If it’s a user error, such situations are where it’s not good to throw errors. It’s best there to be broad in what functions accept, and narrow in what they return.

A good place in which to gain some further details on this topic is the Error Handling chapter of the Eloquent JavaScript book and online resource.

No, that wouldn’t be of much use. That does exactly the same as when you press the stop button on your web browser, so it will stop images from continuing to download, or new windows from loading, but not much else.

So there is no way to just output a json string in javascript and not go any further than that point? (again with the die() php function).

if (myvar == 'output') {
die('i am a string');

That’s what throwing an error does for you. You can issue a stop command after throwing the error, but really it’s not appropriate to write JavaScript in a PHP manner.
Both are quite different languages that each have different environments and situations to worry about.

When you’re writing code in a certain language, it’s pays to write it in the language that you’re writing in, using the techniques that work for that language.
English spoken with a French accent can be quite wonderful. With computer programming languages it’s not quite as nice.

So how would you solve that particular problem? Javascript doesn’t seem to be the right tool for doing what I’m trying to do, which I somehow expected…

Well, what is it that you’re wanting to do?

Well, can we get some more details on what it is that you’re wanting to do?

Sorry for the delay, Paul.

On a certain page of my site, in a certain scenario, I need the script to halt its process and display a message. I’m using PHP’s die() function. It’s not an error that is thrown. However, I’m working now on a version of that site that is not PHP enabled. I was thinking a javascript solution would be nice to achieve the same purpose.

I know it must all sound obscure, and I think that I’m going to try to find another way. A more appropriate one to javascript. My main issue was to try to translate PHP into js, which I realize now is wrong.