react模板中request.js封装的fetch:如何为Spring后端处理json体中的错误

fetch wrapped in request.js in react boilerplate: how to handle error from json body for Spring backend

本文关键字:Spring 后端 json 错误 处理 request js 封装 react fetch      更新时间:2023-09-26

我正在尝试修改这个文件

https://github.com/mxstbr/react-boilerplate/blob/master/app/utils/request.js

问题是它处理statusText中的errorMessage,这不是我可以从Spring后台设置的东西。

在响应的正文中有我的错误消息。

这是我目前为止解决它的方法

我已经尝试了许多不同的方法来使它工作,但我总是打破在这个提交中实现的逻辑:48eecac任何帮助将是感激的

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

在react样板中遇到了同样的问题。基本上,它的工作方式是用来自响应的statusText头来构造Error,而不是响应的主体。

因此,为了在不修改样板代码的情况下处理自定义错误消息,您可以在发送响应的服务器端点的statusText头中直接编写自定义消息。

例如,在Express(4)中,您可以这样设置:

  res.writeHead(401, 'My custom error message');
  return res.send();

然后,在客户端处理错误的地方,你可以像这样访问这个自定义消息:

export function* handleError({ error }) {
  console.log(error.message) // will output "My custom error message"