I am trying to modify this file
https://github.com/mxstbr/react-boilerplate/blob/master/app/utils/request.js
The problem is it handle the errorMessage in statusText, which is not something I can set from my Spring backoffice.
I have my error message in the body of the response.
This is how I solve it so far
I have tried many different way of makint it work it, but I always break the logic implemented in this commit : 48eecac Any help would be appreciated
import "whatwg-fetch";
import { fromJS } from "immutable";
/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON from the request
*/
function parseJSON(response) {
return response.json();
}
/**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
return response.json().then(throwError);
}
/**
* Throw an error with the errorMessage from the response body
*
* @param errorMessage
*/
function throwError(errorMessage) {
throw new Error(errorMessage);
}
/**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {object} An object containing either "data" or "error"
*/
export default function request(url, options = {}) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
.then((response) => (response))
.catch((err) => ({ err }));
}
Stumbled across same issue with react boilerplate. Basically the way it works is that it constructs Error with statusText header coming from response, not the response's body.
So, to handle custom error messages without modifying boilerplate's code, you can write custom message directly in your statusText header on your server's endpoint, where you send your response.
For example, in Express (4) you can set it like this:
res.writeHead(401, 'My custom error message');
return res.send();
Then, on client's side in place where you handle that error you can access this custom message like so:
export function* handleError({ error }) {
console.log(error.message) // will output "My custom error message"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.