Core: Handle Exceptions by Error Code

Created on 6 May 2020  路  4Comments  路  Source: adonisjs/core

Why this feature is required (specific use-cases will be appreciated)?

Currently, there are two ways to handle Exceptions. The first way is to register a single Exception handler using Exception.handle(name, callback), the second is to create a global Exception handler by running adonis make:ehandler. Now what if I want to handle an Exception with a specific code and leave the rest to the default exception handler that Adonis ships with?
For instance, there are many types of HttpExceptions, each with a different code but I want to handle only the one with E_GUEST_ONLY so I tried the following:

// start/hooks.js
const { hooks } = require('@adonisjs/ignitor')

hooks.after.providersBooted(() => {
  const Exception = use('Exception')

  // redirect to / when the user is logged in
  Exception.handle('HttpException', async (error, { response }) => {
    if (error.code === 'E_GUEST_ONLY') {
      response.redirect('/')
    }
    return
  })
})

I would expect to redirect to / only when error.code is E_GUEST_ONLY but fallback to the development exception page on E_ROUTE_NOT_FOUND for example. But the current behaviour is it redirects to / in both cases.

Have you tried any other work arounds?

I tried creating a global handler with adonis make:ehandler but that doesn't suit my need as I want to handle a single exception by code and let Adonis handle the rest.

Are you willing to work on it with little guidance?

If given a starting point, sure.

Question

All 4 comments

Hey @MohamedElidrissi! 馃憢

The global exception handler is extending the BaseExceptionHandler, therefore you can call its handle method.

return super.handle(...arguments)

Example in our blog demo: https://github.com/AdonisCommunity/adonis-blog-demo/blob/master/app/Exceptions/Handler.js#L30

@RomainLanz Oh I don't know how I missed that part, thanks! But still I think having all exception handling done in one class is not super great, if there are multiple exceptions to handle it will be filled with if statements. I guess it would've been better it there was an API like Exception.handle(exceptionName, code, handler).
Anyway, thanks for the help.

You can write abstractions to avoid multiple if statements. I don't think, we will add another way to handle exceptions at this time.

Thanks 馃槃

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

devcaststudio picture devcaststudio  路  3Comments

ghost picture ghost  路  3Comments

milosdakic picture milosdakic  路  3Comments

dezashibi picture dezashibi  路  4Comments

Extarys picture Extarys  路  4Comments