Becoming a software developer – episode XIX

Becoming a software developer – episode XIX

Welcome to the nineteenth episode of my course “Becoming a software developer” in which we will gracefully handle the exceptions and extend logging services with NLog.

All of the materials including videos and sample projects can be downloaded from here.
The source code repository is being hosted on GitHub.


 

Scope

  • Exceptions
  • NLog

Abstract

Exceptions

Dealing with exceptions from the API’s point of view is not an easy task. In the end, we want to return meaningful error codes to the end customers of our service once something goes wrong. It doesn’t matter whether it’s an internal server error or some client validation issue – returning simply an HTTP Status Code that something went wrong doesn’t really help.

Let’s start from the very begging, at first, we can define the custom exception type like this:

Having this base class, we can go further and implement specialized types for different kinds of exceptions:

How can we actually pass further custom error codes? For sure, we could use “magic strings”, but why not move these properties to a separate class and use it in the following way:

Eventually, we can extend the custom exception handler by adding another case for handling our own exception types:

NLog

Default logging available within ASP.NET Core framework is fine, however, quite often we would actually like to use something more sophisticated in terms of logging services. Having the ability to specify different outputs like files, console, databases, external services, defining templates of the messages being logged and so on. This is where libraries like NLog come in handy.

In order to start working with NLog, you need to install the base package in the infrastructure project as well as other 2 extensions designed for ASP.NET Core that will be used by the API. Once the packages are installed, you need to do the 3 things: configure the NLog in Startup class, create a nlog.config where you can specify all of the behaviors, outputs (targets) and much more if needed and mark this file as part of the content that should be copied to the output directory.

Please note that this is a very basic configuration and you can extend it in order to achieve a really sophisticated logging. And finally, you need to copy the configuration file and mark it as a content in the End-to-End test project in order to run the integration tests properly.

In order to use NLog, simply add the following line of code to the particular class and that’s it.

Next

In the next episode, we will handle not only the exceptions but the actual business logic operations within specialized handlers in a more fluent way.

1 Comment Becoming a software developer – episode XIX

  1. Pingback: Dew Drop - June 1, 2017 (#2491) - Morning Dew

Leave A Comment

Your email address will not be published. Required fields are marked *