I'm writing code to deal with errors, and part of this is printing a message to the user (eg "Whoops!")
However, the error code does not know what has gone before, so there is a danger that the error message might be hidden.
For example, what if the error occurs when generating Javascript? Then the HTML output would look like this:
....
&l开发者_运维知识库t;script>
var x = Whoops!
Then as far as the user sees, there is no error message and the page just stops.
The usual solution is to print a barrage of closing tags before you print your error message:
'">--></script></table>Whoops!
The user may see extra stuff appear on the page like ">-->" which isn't neat, but they will see the error message, which is the important thing.
So my question is, what other closing tags can you think of to place in the above string to ensure the user can always see the error message?
EDIT: Yes, I'm aware this isn't the best way and that output buffering can be a better technique. Sorry, should have had in the original question that I can't use use output buffering for this.
The only proper way to make sure an error message is displayed is to close exactly those tags that have been opened before, in the exact order they were opened.
Everything else is just kludgy, broken HTML. It will often work because of the browsers' leniency, but that doesn't make it a good solution.
The best way to deal with this is to do all necessary actions - I assume you are talking about server-side operations here, correct? - before you output the HTML. Either through output buffering, or by filling in all the calculated values into the HTML template as the last step.
That way, you can redirect the user to an error page if something goes wrong, or display a HTML structure dedicated to showing the error.
One of the solutions is to buffer output and to print page only when it is fully rendered. You'll be able to render a proper page with error message if that happens. If even rendering error page fails, you'll be able to just output text message. The user will never see half-completed page.
One thing you can do is add
<script>window.onload = function () { document.write('<!DOCTYPE html>Whoops!'); };</script>
after the </script>
tag in your barrage.
If javascript is enabled, the document.write will blow the existing page away and you'll be left with just the error message.
精彩评论