There must be a reason why auth exceptions are so difficult to access

You can see below I wan’t to know why auth.attempt throws an exception. Deep requiring to get UserNotFoundException seems wrong.

const {UserNotFoundException, PasswordMisMatchException} = require('@adonisjs/auth/src/Exceptions');

class IdentityController {

  async login ({auth, request}) {

    const {email, password} = request.all();

    try {
      await auth.attempt(email, password);
      return {'ok': true};
    } catch (e) {
      if (e instanceof UserNotFoundException) {
        console.log('UserNotFoundException');
      } else if (e instanceof PasswordMisMatchException) {
        console.log('PasswordMisMatchException');
      }
    }

    return {'ok': false};

  }

}

I see that you can create custom exceptions, and this would be great in situations like “NotAuthorizedException” (for example, I made that up), but creating a custom exception handler, for a single controller/action, in some other file, seems like a bad practice.

Is there an easier/documented way to access exceptions like these?

1 Like

e.name === “UserNotFoundException”

Looks like there’s also

e.code E_PASSWORD_MISMATCH
e.code E_USER_NOT_FOUND

I’m a little uncomfortable using any of these undocumented features, but I’ll just make sure I’ve got tests to cover these in case something changes.

Thanks!

@kswope Exceptions have names and code. So E_PASSWORD_MISMATCH is the exception code and UserNotFoundException is the exception name.

You can use names to broadly handle all exceptions. However, the exception code provides granular control, where you can handle each exception in a different.

I personally use exception codes, since they will always remain the same for a given situation.

Thanks,

If anybody is wondering, the docs are here (I should have found it myself)

https://adonisjs.com/docs/4.1/exceptions

Maybe make “code” iterable to make it easier to discover? This is definitely not idiomatic javascript so little things like that would help.

Typescript will help in this space. So my hopes are high for v5

Even Facebook decided to use TypeScript for its famous Jest.js product ([RFC] Migrate Jest to TypeScript). So do not worry, you have done a good choice :slight_smile: @virk

1 Like