錯誤處理

I decided to focus this article on Error handling because it is a very common security problem if it is not handled properly. This topic is very tightly coupled with logging, but for this article, I will just cover error handling.

I saw on many websites that error messages presented to the user (in this case, me) need to be handled properly so they don’t reveal implementation details. You are familiar with the fact that hackers will look deeply into these messages because they know that if they contain information that should not be revealed, they could help them and be like little clues made out of exploitable pieces. 

The most common errors I have seen were detailed internal error messages which are displayed for the user, even sometimes as toast messages.

 

Why are internal errors presented to the users? 

The first problem is always the lack of documentation for the web application. By that, I mean that often due to the time deadlines when setting up the architecture creating the documentation ends up being somewhat neglected. 

Also, logging is often implemented as the last step when setting up the architecture or even after some basic functional code is written. And then, with the lack of documentation about error handling, developers often try to follow the steps of the error handling code they find in the application without any consistent guidance. And in the end, you get messy code, poorly implemented error handling, and exposed data that should not be revealed!

Where should errors be handled in the web application?

 

First, in the mentioned documentation for the web application. There should be defined a policy that will define which types of errors should be handled, what messages should be presented to the user, and what information should be logged.

You can choose where you should handle the errors. It would be eighter on the server side, on the client side, or even both. 

*In my practice, I handled the server errors in the API and sent the proper user message to the client side to be presented to the user if needed. I created a custom error handler for the client errors and presented user-friendly error messages again.

Tips for the error messages style on the client side

In this list, I will focus just on the error messages style, which will be presented for the user eighter they are created on the client side or the server side and sent to the client side.

  • Error and warning messages should be short and use clear and simple language (don’t use technical language). They should provide a short explanation why the problem is occurring and how to fix it (if it is feasible). In short- give direction to the user.

  • Error message images should be applied differently for different scenarios broken, not found, construction, access rights, and other errors.

  • By broken I mean when the Error is 500 when you can not launch some content or load it. Not found I mean when you get 400 error, or the page is not loading. By construction when it is planned site maintenance or some sync of the data. When other errors occur such as some action is not completed successfully you can implement basic toast message with red color. You can also use toast messages when there are some background errors.

  • They can be modified as you wish, they can be closed after the user decides to close them or they can disappear after some time (delay).

  • Don’t use uppercase text

  • Put the error message in the proper place. For example, if you have validation error messages for fields in form, place them so it is easy to understand which message is for each field.

Useful links for error handling:

How to implement toast messages on the client side?

I will explain how to implement and use toast service on the client side, in this example, using Angular 13.

We want to catch and show error messages in two cases, one is when they get from HTTP response and the second one is when we decide to show them because of failure on the client side.

We need first to download ngx-toastr module by running npm i ngx-toastr. You can check out more about ngx toastr on their GitHub. On the site, you can follow the instructions on how to implement it so you can use it in code: add CSS, add ToastrModule (and BrowserAnimationsModule).

To show all error messages we are receiving from the server side, we need to intercept them from HTTP response. In this case we can create and use a custom HTTP interceptor class and implement in it toast service.

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
 
     constructor(private spinnerService: SpinnerService, private toastrService: ToastrService) { }
 
    intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
 
        this.spinnerService.show();
 
        return next.handle(req)
             .pipe(tap((event: HttpEvent) => {
                    if (event instanceof HttpResponse) {
                        this.spinnerService.hide();
                    }
                }, (error) => {
                    if(error.status == 400) {
                        this.toastrService.error("Warning", error.error.Error)
                    } else if(error.status == 500){
                        this.toastrService.error("System error is occured");
                    }
                    this.spinnerService.hide();
                }));
    }
}

In the first example you will see how and when we are catching errors and how we will present them to the user to be user-friendly.

  update(category: CategoryDetail) {
    this.subsink.sink = this.categoryService
      .update(category.id, category)
      .subscribe((data) => {
        if (data != null && data.error) {
          this.toastrService.error("Update failed", data.error);
        } else {
          this.toastrService.success("Update was successful");
          this.loadCategories();
        }
        this._spinnerService.hide();
        this.loadCategories();
      });
  }

In the second example, you will see how to handle errors when getting the response for update functionality.

As you can see, you can easily use ngx-toastr!

 

How to handle errors on the server side?

As I mentioned it is very important for you are handling errors on the server side as well. You are also creating users error messages. 

I will give you just the direction on where to look and how to handle errors in ASP.NET Core 6.

When you check it out, you will see the example using interface IActionResult when sending back the response, where to register Exception Handling Middleware instances, how to create HttpResponseException by extending Exception, how to create an action filer HttpResponseExceptionFilter, etc.

Conclusion

As I mentioned before, error handling goes side by side with logging. Logging is a large topic that needs its own “space,” so it will be covered in the future. There is plenty of documentation on the internet for error handling based on different technologies. But most important is the documentation about it when you decide on the architecture you are going to use.

Also very important is the testing part of the development and also after, because hackers are going to test very uncommon cases to try to invoke errors that you didn’t have in mind to handle them.

Good luck in catching errors!

Cover photo by Eric Mclean!

#error_handling #error_messages

About Version 2 Limited
Version 2 Limited is one of the most dynamic IT companies in Asia. The company develops and distributes IT products for Internet and IP-based networks, including communication systems, Internet software, security, network, and media products. Through an extensive network of channels, point of sales, resellers, and partnership companies, Version 2 Limited offers quality products and services which are highly acclaimed in the market. Its customers cover a wide spectrum which include Global 1000 enterprises, regional listed companies, public utilities, Government, a vast number of successful SMEs, and consumers in various Asian cities.


About vRx
vRx is a consolidated vulnerability management platform that protects assets in real time. Its rich, integrated features efficiently pinpoint and remediate the largest risks to your cyber infrastructure. Resolve the most pressing threats with efficient automation features and precise contextual analysis.