handling newline characters like "\n" and "\r\n" from an python error message in an html file

33 Views Asked by At

I want to show the a FormatViolationError (or error's of other types) to the user. Therefore I programmed a flask webserver that returns the error message in an html file to the user.

The output of the error message has multiple linebreaks included. I want to display these linebreaks to the user but in the html.

Example error: FormatViolationError - description=Payload for Action is syntactically incorrect or structure for Action, details={'cause': "Payload '{'status': 'Accept'}' for action 'GetCertificateStatus' is not valid: 'Accept' is not one of ['Accepted', 'Failed']\n\nFailed validating 'enum' in schema['properties']['status']:\n {'additionalProperties': False,\n 'description': 'This indicates whether the charging station was able '\n 'to retrieve the OCSP certificate status.\\r\\n',\n

The error includes many newline characters as '\n' or '\r\n'. My idea was to replace them with '<br>'.

I have the following code:

def foo():
        try:
            somefunction(bar)
        except Exception as e:
            str_e = repr(e)
            # replace the "python" linebreak with html line breaks
            str_e_with_linebreaks = str_e.replace("\\r", "<br>")
            str_e_with_linebreaks = str_e_with_linebreaks.replace("\\n", "<br>")
            return str_e_with_linebreaks

        return "No errors were found in the provided data"


The html that is returned to the user includes the "<br>" but doesn't have the desired linebreaks.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Processor Result</title>
</head>
<body>
    <h1>Result</h1>
         <p>&lt;FormatViolationError - description=Payload for Action is syntactically incorrect or structure for Action, details={&#39;cause&#39;: &#34;Payload &#39;{&#39;status&#39;: &#39;Accept&#39;, &#39;Accept&#39; is not one of [&#39;Accepted&#39;, &#39;Failed&#39;]&lt;br&gt;&lt;br&gt;Failed validating &#39;enum&#39; in schema[&#39;properties&#39;][&#39;status&#39;]:&lt;br&gt;    {&#39;additionalProperties&#39;: False,&lt;br&gt;     &#39;description&#39;: &#39;This indicates whether the charging station was able &#39;&lt;br&gt;                    &#39;to retrieve the OCSP certificate status.\&lt;br&gt;\&lt;br&gt;&#39;,&lt;br&gt;     &#39;enum&#39;: [&#39;Accepted&#39;, &#39;Failed&#39;],&lt;br&gt;     &#39;javaType&#39;: &#39;GetCertificateStatusEnum&#39;,&lt;br&gt;     &#39;type&#39;: &#39;string&#39;}&lt;br&gt;&lt;br&gt;On instance[&#39;status&#39;]:&lt;br&gt;    &#39;Accept&#39;&#34;, &#39;ocpp_message&#39;: &lt;CallResult - unique_id=8c5f1ba7-0167-4ef3-95cd-6efd88a6720f, action=GetCertificateStatus, payload={&#39;status&#39;: &#39;Accept&#39;}&gt;}&gt;</p>
    <a href="/">Back to input form</a>
</body>
</html>

enter image description here

I am stuck. Most likely replacing the characters is not the way to go. How can I nicely format the error message and include it in an html?

In the actual app.py (flask web server). I include the returned error in the html with:

result = foo(data)
return render_template('result.html', result=result)
1

There are 1 best solutions below

0
Niels Langerak On

You are using repr with generates a printable representational string of the given object.

When you use <br> in your string, it gets converted to &lt;br&gt;. These &lt; and &gt; represent the ascii < and > characters so they can be used in an html string without being recognised as tag. Kinda like how we use the \ in \n in python.

A solution would be to first convert to the printable representational string using repr, and after that you replace the &lt;br&gt; by <br> using String.replace("&lt;br&gt;", "<br>")

It does look like that mean you cannot use the repr(e) because that messes up the code.