Home > Net >  Read error info while API throwing 401 authentication error
Read error info while API throwing 401 authentication error

Time:02-11

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.

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
    }
}

CodePudding user response:

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
}
  • Related