Custom Exceptions in AdonisJS

AdonisJS provides streamlined ways to raise exceptions in your controller or service code, and raise them in a controlled way to the caller.

To create a custom exception -

adonis make:exception RecordNotFoundException

This will create -

√ create  app\Exceptions\RecordNotFoundException.js

Edit the exception to introduce your own errors.

"use strict";

const { LogicalException } = require("@adonisjs/generic-exceptions");

class RecordNotFoundException extends LogicalException {
  /**
   * Handle this exception by itself
   */
  handle(error, { response }) {
    return response.status(404).json({
      error: "Record is not found. Check other universes."
    });
  }
}

module.exports = RecordNotFoundException;

We are trying to raise a 404 with a specific exception message in the above code block.

Now all you need to do is to use this exception in your code. We will take a controller as an example -

// TodoController.js
async index({ request, params }) {
    let { id } = params;
    const todo = Todo.find(id);

    if (!todo)  throw new RecordNotFoundException();
}

PS: This is just an example. Normally you would want to do Todo.findOrFail(id) to automatically raise an exception if the record does not exist. Custom exceptions allow you to have your own validation handlers (for e.g. raise a 403 for heck of it), or custom error messages.

comments powered by Disqus