Меню

Uncaught in promise ошибка 400

I was testing my code to see what would happen if I tried to register an already registered user and when I did that I got the error in the title with the expected error status code, however, I do have a catch statement so I’m not sure why the error is not being caught.

This is the state of the class:

state = {
    data: { username: "", password: "", name: "" },
    errors: {},
  };

This is my code:

doSubmit = async () => {
    try {
      await userService.register(this.state.data);
    } catch (error) {
      if (error.response && error.response.status === 400) {
        const errors = { ...this.state.errors };
        errors.username = error.response.data;
        this.setState({ errors });
      }
    }
  };
export function register(user) {
  http.post(apiEndpoint, {
    email: user.username,
    password: user.password,
    name: user.name,
  });
}

Any help would be appreciated!

asked Dec 5, 2020 at 12:42

Zeffe Struyf's user avatar

4

try catching the error in the register function like this:

export async function register(user) {
    try {
        http.post(apiEndpoint, {
            email: user.username,
            password: user.password,
            name: user.name,
        })
    } catch (error) {
        if (error.message === 'Timeout' 
            || error.message === 'Network request failed') {
            ...
            data.status = 400
            data.errorMessage = "Some error message"
            return data;
        }
        //if (catch other requests...)
    }
}

Then wherever you call the function…

doSubmit = async () => {
      let result = await userService.register(this.state.data);
      if (result.status == 200) {
          do something
      } else if (result.status == 400) {
          do something else
      }
  };

This isn’t the best example but hope it helps!

answered Dec 5, 2020 at 13:05

BlueIcedPen's user avatar

0

catching error in register function instead of doSubmit:-

  • register function:-
export async function register(user) {
  try {
    await http.post(apiEndpoint, {
      email: user.username,
      password: user.password,
      name: user.name,
    });
  } catch(error) {
    return error
  }
}
  • doSubmit function:-
doSubmit = async () => {
    let res = await userService.register(this.state.data);
    if (res.response && res.response.status === 400) {
      const errors = { ...this.state.errors };
      errors.username = res.response.data;
      this.setState({ errors });
    }
  };

answered Dec 5, 2020 at 13:11

lala's user avatar

lalalala

1,1796 silver badges20 bronze badges

Hi @spvjebaraj ,

My guess, that you have placed wrong field name into update object or mismatched list name.
getByTitle uses display names. Update and add objects should include only correct internal names with some exceptions for OData namings.

The errors in a console don’t give all the information. [400] Bad Reques can mean anything. Please check real response message in Chrome Dev Tools in Network tab or by a message within a catch.

OData error message will say more, e.g.:

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The property 'Error' does not exist on type 'SP.Data.[ListName]ListItem'. Make sure to only use property names that are defined by the type."}}}

is a wrong set of field names

{"error":{"code":"-1, System.ArgumentException","message":{"lang":"en-US","value":"List '[Wrong lists' display name]' does not exist at site with URL 'http://....com/sites/site'."}}}

is a wrong lists’ display name

Also, there is no any need to wrap promise into another promise.
$pnp.sp.web.lists.getByTitle(listName).items.getById(itemId).update(fieldValue) is already return a promise. Your function can be:

var updateListItem = function(itemId, listName, fieldValue) {
  return $pnp.sp.web.lists
    .getByTitle(listName)
    .items.getById(itemId)
    .update(fieldValue);
};

To troubleshoot I would suggest:

  1. Check if the list name provided is correct:
var listName = '[your_list]';
$pnp.sp.web.lists.getByTitle(listName).then(console.log); 
// Should return list metadata, if not, then you're trying wrong name
  1. Check field internal names and that you provide corresponding data type format:
var listName = '[your_list]';
var itemId = [item_id];
$pnp.sp.web.lists.getByTitle(listName).items.getById(itemId ).get().then(console.log); 
// Check the list of possible basic fields 
// `WorkDescription` can be named something else, like `WorkDescription0`

Всем привет, на главной странице сайта появилась ошибка, не пойму в чем беда и как разобраться?
Пока на функционал сайта никак не влияет.
О каком порте идет речь?

Uncaught (in promise) Object {message: "The message port closed before a reponse was received."}

015070f257794908997e394ed0c5f867.PNG


  • Вопрос задан

    более трёх лет назад

  • 41734 просмотра

Ошибка была из за приложения Wappalyzer Chrome, отключил и стало все нормально.

Пригласить эксперта

Создаю сайты. Открыл проект, работаю и херак ошибка «Unchecked runtime.lastError: The message port closed before a response was received.», перерыл все, благо нашел этот пост и отключил расширение «MeddleMonkey» все вернулось на круги своя. Если возникнут подобные проблемы, то первым делом проверьте расширения и отключите их все.

AdGuard Антибаннер также выдавал такую ошибку. При отключении плагина больше ошибки не возникало.

Тоже столкнулся с данной проблемой. Решил путем отключения всех расширений, что перестало выдавать ошибку, затем поочередно включал каждое расширение и выявил виновника. У меня это был «Защита от веб-угроз 360».

Отключил расширение Tab Scissors и всё нормализовалось.

Столкнулся с такой же ошибкой. Оказывается, когда делаешь обработку сообщений в chrome.runtime.addListener(hendled()), то выход из обработчика нужно прописывать как return true;
И в content_scripts и в background.


  • Показать ещё
    Загружается…

29 янв. 2023, в 03:07

300000 руб./за проект

29 янв. 2023, в 02:16

700000 руб./за проект

29 янв. 2023, в 01:54

5000 руб./за проект

Минуточку внимания

@ludivn

Hello,

I’ve been using SuperProductivity for a few days now, and I really like it! But everytime I try to end my day by clicking on the button, there is this error window:

Error: Uncaught (in promise): Error: Request failed with status code 400 Error: Request failed with status code 400 at LYNF.e.exports (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:829611) at Rn+g.e.exports (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:1327378) at XMLHttpRequest.p.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:2142253) at XMLHttpRequest.D (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:11438) at l.invokeTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:7190) at Object.onInvokeTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:384270) at l.invokeTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:7111) at i.runTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:2599) at u.invokeTask [as invoke] (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:8240) at _ (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:20167)
! Please copy & report !

exports (webpack:///node_modules/axios/lib/core/createError.js:16:14)
validateStatus (webpack:///node_modules/axios/lib/core/settle.js:17:11)
request.responseURL.indexOf (webpack:///node_modules/axios/lib/adapters/xhr.js:62:6)
listener.call (webpack:///node_modules/zone.js/dist/zone-evergreen.js:759:38)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:402:30)
onInvokeTask (webpack:///node_modules/@angular/core/fesm2015/core.js:28499:32)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:401:59)
task._transitionTo (webpack:///node_modules/zone.js/dist/zone-evergreen.js:174:46)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:483:33)
callback (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1596:13)
scheduleResolveOrReject (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1209:30)
makeResolver (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1116:16)
Ur (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:3718897)
invoke (webpack:///node_modules/zone.js/dist/zone-evergreen.js:368:25)
onInvoke (webpack:///node_modules/@angular/core/fesm2015/core.js:28512:32)
invoke (webpack:///node_modules/zone.js/dist/zone-evergreen.js:367:51)
run (webpack:///node_modules/zone.js/dist/zone-evergreen.js:130:42)
zone.scheduleMicroTask(source, (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1272:35)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:402:30)
onInvokeTask (webpack:///node_modules/@angular/core/fesm2015/core.js:28499:32)

image

Errors as shown by the console:
image
image
image

Other informations:

  • First I installed the app via the GitHub exe file. Everything was ok except for this Error 400. So tried to download it from the Windows store but that didn’t solve the problem.
  • My pc runs on Windows 64
  • Superproductivity version : 6.4.0

I hope someone will tell me what’s happening… (I do have a few ideas, but I’m a total noob in programming so I had better wait for the pros…).

Thank you for your help!

@johannesjo

Thanks for opening this up. It looks like that syncing via dropbox is somehow misconfigured. But this should never crash the application… Could you maybe share your Sync configuration (of course not with the actual credentials, but some placeholder) so I can investiagte?

@ludivn

I’m not sure this are the informations you want me to share:

In super productivity sync settings, syncing is enabled, and I’ve put the authorisation code generated by Dropbox. Sync interval set by default on 1m.
In dropbox, I checked that super productivity was part of the authorized app. I’ve got a folder with a .json file.

That’s for the basic info…

Please let me know what information precisely I should share with you, and where to seek them.

I’m planning on switching to WebDav as Dropbox may be the source of the problem. But maybye I should stay so you could fix a potential bug in the app?

In any case, thanks you for your help!

@johannesjo

Thanks for getting back to me! I am really not sure what is causing this and for me personally dropbox sync runs fine. So please just switch if you have the option. I would love however to try a data export (also created from the settings page) of yours with my own dropbox account. Would you maybe we willing to share one with me (I totally understand, if you don’t)? If so you can send it to contact@super-productivity.com.

@johannesjo

Hi there! With the help of your data I was able to improve the error handling for the particular problem.

If you haven’t changed the sync provider and still want to use Dropbox if possible: It seems like you just forgot one step. You need click «GENERATE TOKEN» after you copied the auth code from the dropbox website. Only then the authentication will work.

Thank you very much for helping me out! Please let me know if you have any further issues!

@ludivn

Hello,

I’ve been using SuperProductivity for a few days now, and I really like it! But everytime I try to end my day by clicking on the button, there is this error window:

Error: Uncaught (in promise): Error: Request failed with status code 400 Error: Request failed with status code 400 at LYNF.e.exports (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:829611) at Rn+g.e.exports (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:1327378) at XMLHttpRequest.p.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:2142253) at XMLHttpRequest.D (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:11438) at l.invokeTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:7190) at Object.onInvokeTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:384270) at l.invokeTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:7111) at i.runTask (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:2599) at u.invokeTask [as invoke] (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:8240) at _ (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/polyfills.bbc1c0564b6a5d42ba73.js:1:20167)
! Please copy & report !

exports (webpack:///node_modules/axios/lib/core/createError.js:16:14)
validateStatus (webpack:///node_modules/axios/lib/core/settle.js:17:11)
request.responseURL.indexOf (webpack:///node_modules/axios/lib/adapters/xhr.js:62:6)
listener.call (webpack:///node_modules/zone.js/dist/zone-evergreen.js:759:38)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:402:30)
onInvokeTask (webpack:///node_modules/@angular/core/fesm2015/core.js:28499:32)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:401:59)
task._transitionTo (webpack:///node_modules/zone.js/dist/zone-evergreen.js:174:46)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:483:33)
callback (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1596:13)
scheduleResolveOrReject (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1209:30)
makeResolver (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1116:16)
Ur (file:///C:/Program%20Files/WindowsApps/53707johannesjo.SuperProductivity_6.4.0.0_x64__ch45amy23cdv6/app/resources/app.asar/dist/main.11bce23b86ad07ade3d1.js:1:3718897)
invoke (webpack:///node_modules/zone.js/dist/zone-evergreen.js:368:25)
onInvoke (webpack:///node_modules/@angular/core/fesm2015/core.js:28512:32)
invoke (webpack:///node_modules/zone.js/dist/zone-evergreen.js:367:51)
run (webpack:///node_modules/zone.js/dist/zone-evergreen.js:130:42)
zone.scheduleMicroTask(source, (webpack:///node_modules/zone.js/dist/zone-evergreen.js:1272:35)
invokeTask (webpack:///node_modules/zone.js/dist/zone-evergreen.js:402:30)
onInvokeTask (webpack:///node_modules/@angular/core/fesm2015/core.js:28499:32)

image

Errors as shown by the console:
image
image
image

Other informations:

  • First I installed the app via the GitHub exe file. Everything was ok except for this Error 400. So tried to download it from the Windows store but that didn’t solve the problem.
  • My pc runs on Windows 64
  • Superproductivity version : 6.4.0

I hope someone will tell me what’s happening… (I do have a few ideas, but I’m a total noob in programming so I had better wait for the pros…).

Thank you for your help!

@johannesjo

Thanks for opening this up. It looks like that syncing via dropbox is somehow misconfigured. But this should never crash the application… Could you maybe share your Sync configuration (of course not with the actual credentials, but some placeholder) so I can investiagte?

@ludivn

I’m not sure this are the informations you want me to share:

In super productivity sync settings, syncing is enabled, and I’ve put the authorisation code generated by Dropbox. Sync interval set by default on 1m.
In dropbox, I checked that super productivity was part of the authorized app. I’ve got a folder with a .json file.

That’s for the basic info…

Please let me know what information precisely I should share with you, and where to seek them.

I’m planning on switching to WebDav as Dropbox may be the source of the problem. But maybye I should stay so you could fix a potential bug in the app?

In any case, thanks you for your help!

@johannesjo

Thanks for getting back to me! I am really not sure what is causing this and for me personally dropbox sync runs fine. So please just switch if you have the option. I would love however to try a data export (also created from the settings page) of yours with my own dropbox account. Would you maybe we willing to share one with me (I totally understand, if you don’t)? If so you can send it to contact@super-productivity.com.

@johannesjo

Hi there! With the help of your data I was able to improve the error handling for the particular problem.

If you haven’t changed the sync provider and still want to use Dropbox if possible: It seems like you just forgot one step. You need click «GENERATE TOKEN» after you copied the auth code from the dropbox website. Only then the authentication will work.

Thank you very much for helping me out! Please let me know if you have any further issues!

I am trying to access a spring boot micro-service hosting on localhost but I am getting following error:

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

Following is my code to access the service:

    import axios from "axios";

export const addProjectTask = (project_task, history) => async dispatch => {
  await axios.post("http://localhost:8080/api/board", project_task);
  history.push("/");
};

I have tried to search on the internet but I am not able to find any solution with the localhost. When I use the above URL in Postman it works fine so the URL is correct.

Edit:
Complete Error:

xhr.js:178 POST http://localhost:8080/api/board 400
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:86
wrap @ bind.js:9
(anonymous) @ projectTaskActions.js:4
(anonymous) @ index.js:8
(anonymous) @ redux.js:477
onSubmit @ AddProjectTask.js:31
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168

I am trying to access a spring boot micro-service hosting on localhost but I am getting following error:

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

Following is my code to access the service:

    import axios from "axios";

export const addProjectTask = (project_task, history) => async dispatch => {
  await axios.post("http://localhost:8080/api/board", project_task);
  history.push("/");
};

I have tried to search on the internet but I am not able to find any solution with the localhost. When I use the above URL in Postman it works fine so the URL is correct.

Edit:
Complete Error:

xhr.js:178 POST http://localhost:8080/api/board 400
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:86
wrap @ bind.js:9
(anonymous) @ projectTaskActions.js:4
(anonymous) @ index.js:8
(anonymous) @ redux.js:477
onSubmit @ AddProjectTask.js:31
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168

Распознавание ошибок — обычное дело для программистов и веб-мастеров, самостоятельно прописывающих программные коды для своих ресурсов. Но порой с сообщением Error сталкиваются обычные пользователи, не имеющие даже приблизительного понятия о том, как быть в сложившейся ситуации. И возникает ступор: что делать? То ли свои действия исправлять, то ли вызывать специалистов, то ли технику уже на свалку везти?

Ошибка Uncaught (in promise) может появляться при работе с JavaScript, браузерами, приложениями и даже мессенджерами. Для понимания причины значение имеет характеристика конкретного сбоя, выводимая после Error.

В любом случае, это ошибка, возникшая в кодировке асинхронной операции с использованием функции обратного вызова. Снижая производительность кода до нуля, формально она не является критичной и, при распознавании, легко устраняется. Однако диагностировать причину бывает крайне трудоемко — именно на это указывает термин Uncaught (“необработанная”). И разобраться с возникающей проблемой по силам только грамотному и внимательному мастеру. Новичку же лучше обратиться за подсказкой к более опытным коллегам.

Для решения проблемы разработчику, как правило, предстоит вручную перебирать все варианты, которые способны вызвать несоответствие и сбой, устраняя конфликт между поставленной задачей и возможностью ее исполнения.

На практике промисы создаются как раз для того, чтобы перехватить ошибку, понять, на каком именно участке кода она возникает. Если бы не использовался Promise, команда просто оставалась бы без исполнения, а пользователь пребывал в неведении: почему та или иная функция не срабатывает? Очевидно, что информирование существенно упрощает задачу и сокращает время на реставрацию процесса.

При определении ошибки, перебирая цепочки, находят функцию, нарушающую логику. Ее обработка приводит к восстановлению работы системы. По сути, promise — это объект, не идущий в систему, а возвращающий в исходную точку сообщение о том, насколько удачно прошла операция. Если же произошел сбой — то какова его вероятная причина.

В то же время многократное использование промисов, связанное с ожиданием ответа, замедляет работу ресурса, утяжеляет его. Поэтому злоупотреблять удобной конструкцией не следует, как бы ни хотелось. Решение заключается в том, чтобы выбрать наиболее важный (или наиболее уязвимый) связующий блок, и именно на него установить необходимый код промис.

Работа по диагностике и обработке ошибок

Собственно, работа по диагностике и обработке ошибок, возникающих при создании сайтов, приложений или даже текстов в редакторе, почти всегда идет по тому же алгоритму: простым перебором исключаешь ошибочные варианты, один за другим.

Наглядный тому пример — поиск ответа на вопрос, почему перестали работать сочетания клавиш Ctrl+C и Ctrl+V. Комбинации “горячих клавиш” могут отказаться реагировать на нажатие из-за заражения вирусом, загрязнения клавиатуры, целого ряда других факторов. Тестируя их один за другим, раньше или позже непременно выйдешь на истинную причину — и тогда уже сможешь ее устранить.

Аналогично необходимо действовать при возникновении ошибки Uncaught (in promise): проверяя строчку за строчкой, каждый показатель, находить неверное значение, направляющее не туда, куда планировалось, переписывать его и добиваться намеченной цели.

Если вы не являетесь разработчиком, не создаете авторских приложений, не владеете профессиональным языком и никогда не касались даже близко программных кодов, но столкнулись с ошибкой Uncaught (in promise), прежде всего проверьте технику на присутствие вирусов. Запущенный злоумышленниками вредитель мог покалечить вашу систему в своих интересах. Второй шаг — попытка восстановления системы в точке, где она благополучно работала ранее. Вспомните, какие обновления вы устанавливали в последнюю очередь, попытайтесь избавиться от них. Если речь не идет о создаваемой вами авторской программе, избавиться от ошибки поможет переустановка поврежденного приложения. Если не поможет и это — остается обратиться к специалисту, способному исправить кодировку. При этом знайте, что проблема — не в “железе”, а в сбое используемого вами программного обеспечения.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Unb ошибка на стиральной машине haier что это означает
  • Unable to find stored game file in cloud storage octogeddon выдает ошибку