Search code examples
javascriptdjangoerror-handlingserverxmlhttprequest

How to send an error message from the server to the client using django and print it to the console?


I have a server request that is supposed to find a file, if it doesn't find that file, in need to print in the js console a custom message saying "I couldn't find file x".

I have tried raising exceptions, raising Http errors, sending custom requests....

But I have no idea how to send both an error (e.g 400, 404...) and a custom message associated with that error.

The purpose of this is, when the XMLHttpRequest() object gets a response, if the status isn't 200, that;s when the error ought to be printed.

I have no interest as to whether this is good practice or not, I just need to be able to do it somehow.

On the server side I am attempting something along the lines of:

raise HttpResponse('I am message')

On the client side I am attempting:

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onloadend = () => {
    if (xhr.status != 200) {
         //print error somehow
    }
}

Solution

  • If you anticipate an error occurring in your back end you can wrap that code in a try catch block and instead of throwing an error you can just get the text from that the error is and send that back. That will result in a 200 response though since you caught the error. So id responded with some sort of object where one of the properties is the status. Something like:

    [
     ['status'] => 'error',
     ['message'] => 'I've fallen and cant get up'
    ]
    

    Then you can just:

     if(response.data.status == 'error') {
    console.log(response.data.message);
    }
    

    Hope that helps.