Pnpjs: Handling errors in catch

Created on 6 Jul 2020  路  3Comments  路  Source: pnp/pnpjs

Category

  • [ ] Enhancement
  • [ ] Bug
  • [x] Question
  • [ ] Documentation gap/issue

I don't know if I'm doing something wrong, but I'm wanting to inspect an error result in order to display a friendly message on the UI. If I catch a simple request, the 'caught' parameter appears to just be a formatted string that has embedded a JSON object in it.

Example (runnable within Chrome SP Editor plugin):

import { sp } from "@pnp/sp/presets/all";

(async () => {

  try {
    const list = await sp.web.lists.getByTitle("FooBar").get();
    console.log("List details: ", list);
  } catch (err) {
    console.log("Error: ", err);
  }
})().catch(console.log)

And you'll observe that err is this:

Error:  Error: Error making HttpClient request in queryable [404]  ::> {"odata.error":{"code":"-1, System.ArgumentException","message":{"lang":"en-US","value":"List 'FooBar' does not exist at site with URL 'https://XXXXXX.sharepoint.com/'."}}}
    at new HttpRequestError (sp.es5.umd.bundle.js:1808)
    at Function.eval (sp.es5.umd.bundle.js:1823)
    at step (sp.es5.umd.bundle.js:726)
    at Object.eval [as next] (sp.es5.umd.bundle.js:707)
    at fulfilled (sp.es5.umd.bundle.js:697)

I'd really like err in the catch so simply be that referenced object, so I would just return out err.message.value or some such.

documentation investigate enhancement

Most helpful comment

Reopening this to remind us to create an error handling article in the docs to cover this as well.

All 3 comments

Hi @jimmywim,

You can actually get more from the error than just a message:

sp.web.lists.getByTitle('No such a list').get()
  .then(console.log)
  .catch((err) => console.log(err.response))

image

So, if it's just about status code, it's there.

Can we get the error text returned from SharePoint though? Specfically, from my example, the text: "List 'FooBar' does not exist at site with URL 'https://XXXXXX.sharepoint.com/'. Especially helpful as this is localized.

EDIT: I just realized that is probably in the body stream of the response.

import { sp } from "@pnp/sp/presets/all";

(async () => {

  try {
    const list = await sp.web.lists.getByTitle("FooBar").get();
    console.log("List details: ", list);
  } catch (err) {
    var resp = await err.response.json();
    console.log(resp);
  }
})().catch(console.log)

Returns:

image

That's good enough for me, thanks!

Reopening this to remind us to create an error handling article in the docs to cover this as well.

Was this page helpful?
0 / 5 - 0 ratings