Is there a better way to Handle exceptions


#1

I’m new to AdonisJS and there are a couple of things I’d like to get clarifications on.

I have several custom exceptions as shown in the image below
53%20PM

And I’m using them in my service class as shown below:

class HelperService {
  verifyRegisteredUser(user, message) {
    if (user)  {
      throw new UserExistException(message)
    }
  }

  handleResourceNotExists(resource, message) {
    if (!resource)  {
      throw new ResourceNotExistException(message)
    }
  }
}

And here’s my UserExistException class

'use strict'

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

class UserExistException extends LogicalException {
  /**
  * Handle this exception by itself
  */
  handle (error, { response }) {
    return response.status(409).json({
      message: error.message
    })
  }
}

module.exports = UserExistException

I’d like to know if there’s a better way to achieve this as I can imagine what it will be like to create about 15 custom exceptions


#2

There is no need to create multiple custom exceptions, unless you want to return a different response for each of them.

Simple throw new Error() will work fine. Custom exceptions are helpful, when you have a different response type for them.


#3

Thanks. This has really helped