This page looks best with JavaScript enabled

Custom Exceptions in AdonisJS

 ·   ·  ☕ 2 min read

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 -

1
adonis make:exception RecordNotFoundException

This will create -

1
√ create  app\Exceptions\RecordNotFoundException.js

Edit the exception to introduce your own errors.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"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 -

1
2
3
4
5
6
7
// 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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things