Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read error info while API throwing 401 authentication error

My API returned 401 error while the user token expired or was not valid and it’s returning status code 401 and payload with the error message and code like below.

enter image description here

I want to read this response body while getting 401 errors.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can able to read status code like below

let response = request.task?.response as? HTTPURLResponse
if let statusCode = response?.statusCode, statusCode == 401 {
   //Retry with new token
}

How to read response body message?

Can anyone help me with this?

Through postman (check above screenshot for reference) I can see the message and 401 code but on Swift with Alamofire How can I read the message?

EDIT:

I am trying to read this body/data in Request intercpter like below:

func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
    let response = request.task?.response as? HTTPURLResponse
    if let statusCode = response?.statusCode, statusCode == 401, request.retryCount < retryLimit {
       //Refresh token and retry
    }
}

>Solution :

HTTPURLResponse doesn’t have the data, but the request, as a DataRequest has it:

if let dataRequest = request as? DataRequest, let data = request.data {
    // parse the data
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading