Search code examples
javascriptnode.jspromise

populate my throw object with error message in json response


I want to populate my error object {'status': response.status, 'msg': ''} with the error message present in the JSON Response of the API if there is any, otherwise throw the error object without any message. But throw {'status': response.status, 'msg': ''} statement is hit before the json_response promise is evaluated and everytime i get the empty message.

How can I populate the message attribute in my error object?


    return await fetch(url.toString(), {
        method: 'post',
        headers: get_headers(url, request_body),
        body: JSON.stringify(request_body)
    })
        .then((response) => {
            console.log(`API Status: ${response.status} API ${url.toString()}`)

            if (!response.ok) {
                // response.json()
                //     .then(json_response => {
                //         console.log(json_response)
                //         logger.error(json_response)
                //         throw {'status': response.status, 'msg': json_response?.errorMessage?.message}
                //     })
                //     .catch((e)=>{
                //         throw e
                //     })
                throw {'status': response.status, 'msg': ''}
            }

            return response.json()
        })
        .then((json_response) => {
            return json_response

        })
}

Solution

  • But throw {'status': response.status, 'msg': ''} statement is hit before the json_response promise is evaluated and everytime i get the empty message.

    Well you can't have both at once! Also you'll need to return the promise with the error response:

    .then((response) => {
        console.log(`API Status: ${response.status} API ${url.toString()}`)
    
        if (!response.ok) {
            return response.json()
    //      ^^^^^^
               .then(json_response => {
                   console.log(json_response)
                   logger.error(json_response)
                   throw {'status': response.status, 'msg': json_response?.errorMessage?.message}
               });
        }
    
        return response.json()
    })
    

    Btw, when inspecting a http error response, I would recommend to always check the Content-Type header before parsing it as JSON. Many error responses are still html pages or plain text, even for JSON APIs.