jedu
jedu

Reputation: 1341

Sending error from Nodejs express to Jquery

I am trying to figure out an appropriate way to send an error to a failed jquery post request.I have been looking everywhere to figure out a proper way to do this.

If I make a jquery post request like this :

 $.ajax({
            type: "POST",
            url: "/someRoute",
            data: {
                data: $(".data").val(),
            },
            success: function (data) {
                console.log("Success")
            },
            error:function(err){
                console.log(err)
                $.toast({
                    title: err.message,
                    subtitle: 'Just Now',
                    content: err.message,
                    type: 'danger',
                    delay: 5000
                });
            }
        })

Nodejs

router.post("/someRoute",(req,res)=>{
       try{
           if(!someCondition){
               const err = new Error('Item Not Found')
               err.statusCode = 404;
               throw err;
           }
       }
       catch(err){
             res.status(404).send(err)
      }

    }

The problem is that the message I have attached to the error object in Nodejs by doing

const err = new Error('Item Not Found') is not avalaible in my jquery error function. The error message that I am getting in my console is

abort: ƒ ( statusText )
always: ƒ ()
catch: ƒ ( fn )
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ ( key )
overrideMimeType: ƒ ( type )
pipe: ƒ ( /* fnDone, fnFail, fnProgress */ )
progress: ƒ ()
promise: ƒ ( obj )
readyState: 4
responseJSON: {statusCode: 404}
responseText: "{"statusCode":404}"
setRequestHeader: ƒ ( name, value )
state: ƒ ()
status: 404
statusCode: ƒ ( map )
statusText: "Not Found"
then: ƒ ( onFulfilled, onRejected, onProgress )
__proto__: Object

When I am handeling a specific error I want to display the error message to the client but all I know from the error message that I received is that it ended up in 404.

Upvotes: 2

Views: 191

Answers (1)

MartyBoggs
MartyBoggs

Reputation: 381

Messages in standard error objects don't get sent.. maybe cause they can't be stringified. Try this instead

res.status(404).send({error: err.message});

Upvotes: 1

Related Questions