UI Development

Best Practices in Error Handling

Always write a code assuming that “yes your code may fail”. Error handling depends on the company’s architecture.

Different most common types of errors are as under-

a) Syntax Errors – These errors comes due to the wrong syntax of the code. if suppose in a file this error has happened whole file code will not run.

In order to avoid them we should always use a proper syntax according to the specs.

b) Type Errors – These type errors generally happens when the value is not of the type which is declared.

In order to avoid them we should always the type should be in accordance with what is expected to be.

c) Reference Errors- These happens when we generally refer a value but it doesn’t exist.

In order to avoid them we should always we should declare and assign the values first before we referencing it.

d) URI Errors – These errors come when the URI is malformed.

In order to avoid them we should always look in for the proper URI methods.

e) Range Errors – These error comes when we have added the range that is not valid.

In order to avoid them we should always provide a valid range value.

In order to handle these errors we can follow following practices as under-

1)  We can always surround our code with the try and catch block and try to log the proper message

2) We can log JS error to our server. This actually depends on the architecture of the site and the user base.  Suppose we are logging every window.onerror() call to our servers.

     For a small user base site we can manage it but suppose the site with the heavy traffic with some millions of users.

     This will again ensures that we are not flooding our server with millions of useless errors.  So, reducing the logging size

     and randomising it is a good technique to see the significant errors only we can do something like this-

3) We can also throw our own error like

Note: Error should be thrown in lower level implementation of the code like utilities, libraries but we should try and catch in higher level implementation like client side business logic, specific operation.

4) we can stack trace the javascript errors. We can find the functions order, from the most  latest ones to the global scope

5)  Async operations where we use now async await where error can be catch by making a global error handler factory.

we can use Error class provided by the ES6, We can create some most common error types and then export it like below

and then we can made use of these error in our code like

when we throw a custom error like above then we can also check the name of the error like-

Catching error when a promise is returned. Before rejecting a promise we can also update user with more useful message and  what went wrong and  they can to do next.

 

 

About The Author