English 中文(简体)
轴心处理错误
原标题:Axios handling errors

我试图理解“javascript”的意思比阿西斯好。 我所预言的是处理请求书js中的所有错误,并且只要求任何地方的请求功能,而不必使用<条码>(<> > 渔获/代码>。

In this example, the response to the request will be 400 with an error message in JSON.

错误是:

Uncaught (in promise) Error: Request failed with status code 400

我发现的唯一解决办法是增加<条码>副渔获物(() =>{}>,在有些地方,js,但Im试图避免这样做。 是否可能?

Here s the code:

Request.js

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: {  Authorization :  Bearer   + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }

  ...

  return axios(config).then(
    function (response) {
      return response.data
    }
  ).catch(
    function (error) {
      console.log( Show error notification! )
      return Promise.reject(error)
    }
  )
}

某些地方。

export default class Somewhere extends React.Component {

  ...

  callSomeRequest() {
    request( DELETE ,  /some/request ).then(
      () => {
        console.log( Request successful! )
      }
    )
  }

  ...

}
问题回答

如果你想要处理你请求模块中的所有基本错误,而不必使用<条码>、<>>/代码>,那么Axios办法就是使用>-interceptor关于答复:

axios.interceptors.response.use(function (response) {
    // Optional: Do something with response data
    return response;
  }, function (error) {
    // Do whatever you want with the response error here:

    // But, be SURE to return the rejected promise, so the caller still has 
    // the option of additional specialized handling at the call-site:
    return Promise.reject(error);
  });

如果你从轴心拦截器中回来错误,那么你也可以通过<条码>副渔获物(栏目)使用常规方法,例如:

axios.get( /api/xyz/abcd )
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser 
      // and an instance of http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log( Error , error.message);
    }
   
  });

如果你想进入整个错误机构,就这样做:

 async function login(reqBody) {
  try {
    let res = await Axios({
      method:  post ,
      url:  https://myApi.com/path/to/endpoint ,
      data: reqBody
    });
  
    let data = res.data;
    return data;
  } catch (error) {
    console.log(error.response); // this is the main part. Use the response property from the error object
    
    return error.response;
  }
}

You can go like this: error.response.data
In my case, I got error property from backend. So, I used error.response.data.error

我的法典:

axios
  .get(`${API_BASE_URL}/students`)
  .then(response => {
     return response.data
  })
  .then(data => {
     console.log(data)
  })
  .catch(error => {
     console.log(error.response.data.error)
  })

如果你在等待审判时使用 子

export const post = async ( link,data ) => {
const option = {
    method:  post ,
    url: `${URL}${link}`,
    validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    data
};

try {
    const response = await axios(option);
} catch (error) {
    const { response } = error;
    const { request, ...errorObject } = response; // take everything but  request 
    console.log(errorObject);
}

I Trial using the try{}rip} 这种方法对我不可行。 然而,当我转而使用<代码>then(......)的副渔获物(......)时,Axios Error被正确地抓住,我可以与他一道工作。 当我尝试前者时,我看不见AxiosError,而是向我说,所发现的错误没有界定,而这正是在《国际调查》中最终显示的。

我不敢肯定为什么会发生这种情况。 因此,我建议采用上文提及的“传统<代码>then(......)”方法,以避免向用户投掷未界定的错误。

关于可再使用性:

造成档案错误Handler。 j)

export const errorHandler = (error) => {
  const { request, response } = error;
  if (response) {
    const { message } = response.data;
    const status = response.status;
    return {
      message,
      status,
    };
  } else if (request) {
    //request sent but no response received
    return {
      message: "server time out",
      status: 503,
    };
  } else {
    // Something happened in setting up the request that triggered an Error
    return { message: "opps! something went wrong while setting up request" };
  }
};

然后,当你发现轴心错误时:

Just import error handler from errorHandler.js and use like this.
  try {
    //your API calls 
  } catch (error) {
    const { message: errorMessage } = errorHandlerForAction(error);
     //grab message
  }

如果我正确理解,请设职能中的then,只有在请求成功时才能被称作,而且你想忽视错误。 如果轴心要求是成功的,而且如果失败,永远不会予以拒绝,那么你可以作出新的承诺。

更新的法典将考虑这样的内容:

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: {  Authorization :  Bearer   + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }


  return new Promise(function(resolve, reject) {
    axios(config).then(
      function (response) {
        resolve(response.data)
      }
    ).catch(
      function (error) {
        console.log( Show error notification! )
      }
    )
  });

}
axios
  .get(`${API_BASE_URL}/students`)
  .then(res => {
     return res.data
  })
  .then((data)=> {
     console.log(data)
  })
  .catch(error => {
     console.log(error)
  })

以这种方式审判,处以罚金

将请求功能从任何地方转移,无须使用渔获。

首先,虽然在一个地方处理大多数错误是一个好的想法,但与请求并不容易。 某些错误(例如400个验证错误,如“用户名称”或“无效电子邮件”)应当予以通过。

因此,我们现在使用一种基于智慧的职能:

const baseRequest = async (method: string, url: string, data: ?{}) =>
  new Promise<{ data: any }>((resolve, reject) => {
    const requestConfig: any = {
      method,
      data,
      timeout: 10000,
      url,
      headers: {},
    };

    try {
      const response = await axios(requestConfig);
      // Request Succeeded!
      resolve(response);
    } catch (error) {
      // Request Failed!

      if (error.response) {
        // Request made and server responded
        reject(response);
      } else if (error.request) {
        // The request was made but no response was received
        reject(response);
      } else {
        // Something happened in setting up the request that triggered an Error
        reject(response);
      }
    }
  };

然后,你可以像现在这样利用请求。

try {
  response = await baseRequest( GET ,  https://myApi.com/path/to/endpoint )
} catch (error) {
  // either handle errors or don t
}

一种处理对应类型中轴差错误的方法,对为我工作的流体而言。

.....
.....
try{
   .....
   .....
   // make request with responseType:  stream 
   const url = "your url";
   const response = axios.get(url, { responseType: "stream" });
   // If everything OK, pipe to a file or whatever you intended to do
   // with the response stream
   .....
   .....
} catch(err){
  // Verify it s axios error
  if(axios.isAxios(err)){
    let errorString = "";
    const streamError = await new Promise((resolve, reject) => {
      err.response.data
        .on("data", (chunk) => {
           errorString += chunk;
          }
        .on("end", () => {
           resolve(errorString);
         }
      });
    // your stream error is stored at variable streamError.
    // If your string is JSON string, then parse it like this
    const jsonStreamError = JSON.parse(streamError as string);
    console.log({ jsonStreamError })
    // or do what you usually do with your error message
    .....
    .....
  }
  .....
  .....
}
   
  
let response;
await axios({ method, url, data: body, headers })
.then(data => { response = data })
.catch(error => { response = error.response; });

页: 1 物体,无需担心轴心错误,你可以处理基于<代码>response.status的物品。

我在这样的情景中,我没有机会查阅申请的后端,并且利用一种工具来验证这些田地,回馈诸如<代码>response.data:

"Error: Username  UsuarioTeste  is already taken.."

由于这是一个标准信息,我需要加以调整,以提交给用户,因此我使用了以下程序:

.catch((error) => {
      const errosCadastro = error.response.data;
      const listaErros = errosCadastro.split("
");
      listaErros.map(erro => {
        if (erro.includes("Error")) {
          const start = erro.indexOf(":") + 2;
          const end = erro.indexOf(" ", start) - 1;
          const fieldName = erro.substring(start, end);
          const ErroCampo =
            fieldName == "Username" ? `Já existe um usuário cadastrado com o nome: <span style="font-weight: bold;"> ${this.name}</span>. <br>`
              : fieldName == "Email" ? `Já existe um usuário cadastrado com o email: <span style="font-weight: bold;"> ${this.email}</span>. <br>`
                : fieldName == "registro" ? `Já existe um usuário cadastrado com o registro: <span style="font-weight: bold;"> ${this.record}</span>. <br>`
                  : "";

          errorMessage = errorMessage.concat(ErroCampo);
        }
      })
  • 形成轴心:

    export const api = axios.create({
        baseURL:  /api 
    });
    

- 反应的中值

api.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response && err.response.status >= 500) {
      // Handling for server errors (status code >= 500)
      const { response } = err;
      const message = createErrorMessage(err);

      if (message) {
        // Return the error or additional information for further handling
        // you could populate the store here if you have a global store 
        return {
          error: {
            contentType: response.headers[ Content-Type ] || response.headers[ content-type ],
            message: createErrorMessage(err)
          }
        };
      }
    }
    // this will be returned if the error status is less than 500
    // this will be caught in the try/catch block when axios fetching executed. so you could catch and handle in there
    return Promise.reject(err); // Rejection if error doesn t meet conditions
  }
);

- 以上使用的是通用功能

export const createErrorMessage = (error: unknown) => {
    // When Axios encounters an error during an HTTP request or response handling, it creates a specific Axios error object
    if (axios.isAxiosError(error)) {
        const apiError = error.response?.data;
        if (typeof apiError ===  string  && (apiError as string).length > 0) {
            return apiError;
        }
        return apiError?.message || apiError?.error || error.message;
    }
    // Network errors
    // timeout errors
    // CORS errors
    if (error instanceof Error) {
        return error.message;
    }
    if (
        error &&
        typeof error ===  object  &&
         message  in error &&
        typeof error.message ===  string 
    ) {
        return error.message;
    }

    return  Generic error message ;
};




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签