I didn’t even know this was v1. I thought our project was using v2…
Since I couldn’t tell if your reply was sarcastic (either way it didn’t shed any light on my problem), I spent some time writing the snippet myself.
===========================
The main difference between Aurelia’s HttpClient and the fetch api is that in Aurelia failures will ALWAYS throw an error.
I.e. in Aurelia there is no distinction between (a) “failed because network error” (which would throw in fetch
), and (b) “failed because some more benign problem such as bad request” (which would not throw in fetch
and would require to check the status code).
Aurelia makes it simpler.
Scenario 1 : We only want to process a success (any success) or an error (any error)
We only need the payload (i.e. content) of a success, and only want to catch the error code or message.
import {HttpClient, HttpResponseMessage} from "aurelia-http-client";
export interface MyResultType {
myValue: number;
}
....
try {
const result:MyResultType = (await myHttpClient.get("http://my-get-url")).content;
console.log(result.myValue);
} catch (e) {
const err = e as ErrorHttpResponseMessage;
console.error(err?.message ?? "An error occurred");
console.error(err?.statusCode);
} finally {
console.log ("all done!");
}
Notice the .content after the get.
Scenario 2 : We want to process a success (any success) or a SPECIFIC error
We only need the payload (i.e. content) of a success, but this time we want to study the errors.
try {
const result:MyResultType = (await myHttpClient.get("http://my-get-url")).content;
console.log(result.myValue);
} catch (e) {
const err = e as ErrorHttpResponseMessage;
switch(err.statusCode) {
case HttpResponseStatus.BAD_REQUEST:
console.error(err.response); // <-- if we assume your response is a raw string containing only the error message
console.log(err?.message ?? "Bad request fallback"); // <-- if we assume you made it a message
console.error(((err.content) as MyElaborateErrorObject).myElaborateErrorField); // <-- if your error contains an object
break;
default:
console.log(err?.message ?? "An error occurred");
}
console.log(err.statusCode);
} finally {
console.log ("all done!");
}
Notice how the .content was still there
Scenario 3 : We want to fully process the success
We only need the payload (i.e. content) of a success, but this time we want to study the errors.
try {
const response:HttpResponseMessage= await myHttpClient.get("http://my-get-url");
switch(response.statusCode) {
case HttpResponseStatus.OK:
...
case HttpResponseStatus.NO_CONTENT:
...
}
// Maybe you also want to study the success response even more!
if (response.headers.get("my-header")) === "something") {
...
}
} catch (e) {
.... // Same as before
}
Notice how the .content is no longer there