Actually, @texnixe, I think I spoke too soon. The code above is not working for me
In your javascript code above, the catch()
method will get called only if the Promise object is not fulfilled, or gets explicitly rejected - e.g., if there is a network error and we don’t get a response. Even if the response has a code of ‘500’, what gets called is the then()
method. I believe the proper way to check success based on response codes should be:
<script>
let url = 'http://kit.test/testpattern';
fetch(url)
.then(function(response){
if(response.ok){
// this gets called if response code is in the 200 range:
console.log(response.statusText);
} else {
// this will get called otherwise - it will 'reject' the response,
// so it gets trapped by the 'catch' method below:
throw new Error(response.statusText);
}
})
.catch(function(error){
console.log(error);
});
</script>
However, the ‘response.statusText’ is a read-only string that always corresponds to the response code - i.e., “OK” if ‘200’, or “Internal Server Error” if ‘500’. So, in the example above, the ‘response.statusText’ that gets logged onto the console is always ‘Internal Server Error’.
I believe that if we want to pass a custom error code, we should be doing it in the body of the response. The strange thing is, that according to the docs on Kirby’s Response
class, the first argument of the class constructor should indeed set the response body - so, in your example above, the body should be set to ‘Invalid CSRF Token’. In theory, we should probably be able to get our custom error code with something like this:
throw new Error(response.body.text);
But here is what is happening:
- when we are not using ‘fetch’ or ajax, the response body works as expected, and gets (properly) rendered into a new HTML page
- but if we use ‘fetch’ or ajax, the response body doesn’t seem to be found at all:
response.bodyUsed
always returns false
, response.body
is empty, and response.body.text
is undefined.
So, I’m still stuck trying to find a way to return a custom error message… Do you think this is an issue with the Response class, or is there something obvious in the javascript that I’m overlooking?