Answer the question
In order to leave comments, you need to log in
How to combine try...catch... for async/await and Promise.catch()?
Vue and React projects have a service for working with api, in which error handling is performed for each operation according to the following scheme:
import axios from 'axios';
const posts = {
getPosts(){
return axios
.get('https://jsonplaceholder.typicode.com/p2osts/1')
.then(r => r.data)
.catch(err => handleError(err, 'posts.getPosts()'))
}
}
/**
* Localize error sourse for debuging usability
*
* @param {*} err - catched error
* @param {string} apiMethod - name like 'posts.getPosts()'
*/
function handleError(err, apiMethod){
console.error(`Error in api().${apiMethod}:`)
console.error(err);
// code for error logging in production
}
export function api(){
return{
posts
}
}
try{
const data = await api().posts.getPosts();
console.log( data );
}
catch{
console.log( 'Показать уведомление об ошибке' );
}
Answer the question
In order to leave comments, you need to log in
.catch(handleError('posts.getPosts()'))
function handleError(name) {
return (err) => {
throw err;
};
}
if you want to get an error in the component, modify the service so that it returns the {data, error} object and in the component see what came, error or data
import axios from 'axios';
const posts = {
getPosts(){
return axios
.get('https://jsonplaceholder.typicode.com/p2osts/1')
.then(r => {data: r.data})
.catch(error=> {
handleError(error, 'posts.getPosts()')
return {error}
})
}
}
import axios from 'axios';
const posts = {
getPosts(){
return axios
.get('https://jsonplaceholder.typicode.com/p2osts/1')
.then(r => r.data)
.catch(error=> {
handleError(error, 'posts.getPosts()')
throw err;
})
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question