ServerCode Error handling

I would like to get som proper error handling in the APIs that I create. I am ysing try/catch clauses to catch things that I want to catch, but when I do this, errors are handled on the server side, not sent to the client. To do that, I have to use the New Server Code Error block outside of a try/catch clause.

So I was wondering if there are some best practices or good code examples of doing simple error handling with server side APIs, so that:

  1. Uncaught errors are handled gracefully, and a general error code for this sent back to the client with a status code other than 200
  2. “Known” errors can be given an error code other than 200 back to the client, with more specific messages.

Then I can catch these on the client side and give some more tailored feedback to the user…

Hello @Egil_Helland

It could look like on screenshot below.

image

Fantastic @Dima ,

That was almost too easy :slight_smile:

How can I pick the error codes up then on the calling app side? When that API call fails on the front end app calling it, I see the error message and that the GET request logs as a 400 error, but how can I check for that 400 code (not the error text message) in my try/catch clause on the front end app and present the user with a conditional message there?

I want to provide (in this case) a 406 error, and then if that is the error returned from the API, present the user with a particular message (localized), so that I cannot use the error message returned from the API directly.

image

This example works for me. Is it what you want?

Yes, but I need the returned result, so I have that ticked off. When doing so, the error thrown does not retain the error code it seems to me. Do you see the same?

There is no result because the request is failed(we throw the error).

Do you see the same?

No, my error code and status passed correctly.

You are correct @Dima , I as trying to reach the wrong property in the error object! Works like a charm, thanks for helping out!