Having trouble with how MATLAB interpret's the message of a server error when type is of application/json.
Problem
Calling a local API, the following error is returned:
{"errorCode":401,"message":"Access to mylocalapi not authorized"}
Calling this using webread in MATLAB, the following exception is generated. Note the message has been stripped out of the exception.
Error using matlab.internal.webservices.HTTPConnectionAdapter/copyContentToByteArray
The server returned the status 401 with message "" in response to the request to URL http://mylocalapi
Error in webread (line 125)
[varargout{1:nargout}] = readContentFromWebService(connection, options);
Assessment
The error handler in HTTPConnectionAdapter does not seem to find the message part of the error. The response was compliant with the odata and Google API standards, but need to recognise there is no clear standard here. My problem is that the content has been stripped out by the time the response is returned as an MException object.
The only way around this seems to be to define a custom ContentReader in weboptions, however this has a performance impact across the full application, due to local disk i/o and poor ContentReader code on the part of the user.
Otherwise, the HTTPConnector generates the following MException
e = MException with properties: identifier: 'MATLAB:webservices:StatusError' message: 'The server returned the status 401 with message "" in response to the request to URL http://mylocalapi.' cause: {0×1 cell} stack: [11×1 struct]e.stack(1)ans = struct with fields: file: 'D:\MATLAB\R2018b\toolbox\matlab\external\interfaces\webservices\restful\+matlab\+internal\+webservices\HTTPConnector.m' name: 'HTTPConnector.copyContentToByteArray' line: 361
Might it be possible to extend the MException class to have a HTTPException with additional fields such as the full error response?
For info, the following weboptions are being sent with the request.
options = weboptions with properties: CharacterEncoding: 'auto' UserAgent: 'MATLAB 9.5.0.1067069 (R2018b) Update 4' Timeout: 5 Username: '' Password: '' KeyName: '' KeyValue: '' ContentType: 'json' ContentReader: [] MediaType: 'application/json' RequestMethod: 'get' ArrayFormat: 'json' HeaderFields: {1×2 cell} CertificateFilename: 'D:\MATLAB\R2018b\sys\certificates\ca\rootcerts.pem'
Apologies if this is non-reproducable, however it is using a local service.
Best Answer