B
B
bormor2019-07-22 13:48:20
JavaScript
bormor, 2019-07-22 13:48:20

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

Those. on call - api().posts.getPosts(), a call is made to the server api and if an error occurs, it is displayed in the console and logged in the cloud service.
How to add a notification in a component that uses such a service, which will show the user the text in case of an error?
This option doesn't work:
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

2 answer(s)
M
Michael, 2019-07-22
@bormor

.catch(handleError('posts.getPosts()'))

function handleError(name) {
  return (err) => {
    throw err;
  };
}

V
Vladimir, 2019-07-22
@Casufi

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 question

Ask a Question

731 491 924 answers to any question