Handling Exceptions in AdonisJS

Handling Exceptions in AdonisJS

One question I think about is "how to best handle exceptions?", I work with AdonisJs version 4.1 and in this article, I will show how AdonisJs makes handling exceptions easy.

What are exceptions?

Exceptions are events that occur and cause the running of a program to be disrupted. When they occur they bubble to the top of the call stack looking for a handler at each level when one is found, the program continues running from there. I have always handled exceptions with the try-catch-finally block, so when a program is disrupted in the try block, it gets handled in the catch block, and no matter what happens in the try or catch block the finally block runs. The finally block is optional, leave it out if you have nothing to run after the try-catch block.

  function() {
    try {
      // Block of code to be executed
    } catch(error) {
      // Handles exceptions
     } finally {
       // Runs after no matter the outcome of the code.
    }
  }

Handling exceptions in AdonisJs 4.1

AdonisJs following its principle of putting the developer's joy first, have gone ahead to ensure that you worry less about configuration by ensuring that some features come prebuilt so you just have to plug and code. To learn more about AdonisJs, follow this link. How does one handle exceptions during an HTTP life cycle in AdonisJs?

  • Firstly, one could use the try-catch block and return an error message in the catch block if an exception is thrown, in any method handling an HTTP request or any other running process.
  • Secondly, AdonisJs comes prebuilt with a global exception handler, which can be configured to match the developer's need, by default it handles all exceptions and displays them in a nice format. To use the AdonisJs exception handler, run the command, adonis make:handler, once successful a Handler.js file is created in the exceptions folder. It contains an ExceptionHandler class which inherits from the BaseExceptionHandler class. The class contains two methods, the handle method which returns the error message, and the report method which is meant for reporting errors either to the stderr or via an application management tool. What if I need to create exceptions to handle an error, for example, I need to return a not found error message, then we have to run adonis make:exception notFound, which creates a NotFoundException class in the exceptions folder located in the app folder. The exception class contains only a handle method, though you can add a report method to it and it inherits from the LogicalException class. Then I import the exception into the file where it is needed, const NotFoundException = use('App/Exceptions/NotFoundException'). When there is a need to call the exception, it is called by using throw new NotFoundException() and if you need to pass an error message then it will be throw new NotFoundException('X not found'). To further handle it you can look at the block of code below.

    async handle (error, { request, response }) {
      if(error.name == 'NotFoundException') {
        return response.status(404).send({
          status: 'Not Found', 
          error: error.message // or your error message
        })  
      }
    
    // To handle other forms of exception/error
    
      return response.status(500).send({
        status: 'System Error', 
        error: 'System encountered an error' // or your error message
      })
    }
    

    Or

  const NotFoundException = use('App/Exceptions/NotFoundException')

  async handle (error, { request, response }) {
    if(error.name == 'NotFoundException') {
      throw new NotFoundException().handle(error, response)  
    }

  // To handle other forms of exception/error

    return response.status(500).send({
      status: 'System Error', 
      error: 'System encountered an error' // or your error message
    })
  }

And in the NotFoundException.js file, the handle method will contain

  async handle (error, response}) {
      return response.status(404).send({
        status: 'Not Found', 
        error: error.message // or your error message
      })  

  }

Finally, I hope you enjoy using the adonis exception module on your next projects.