Usage

Error Handling & i18n

Understand how SimpleAuthException handles 401 Unauthorized responses and i18n translations.

When ctx.simpleAuth.authenticate() fails, it throws a SimpleAuthException. This exception is thrown in any of the following cases:

  • The configured apiKeyHeader is missing from the request.
  • The header value in the request is empty or contains only whitespace.
  • The configured apiKeyValue in config/simpleauth.ts is empty or contains only whitespace.
  • The request header value does not match apiKeyValue (compared using timing-safe safeEqual).

Exception Properties

SimpleAuthException extends @adonisjs/core/exceptions's Exception class with the following default properties:

PropertyValue
status401
code'E_SIMPLE_UNAUTHORIZED_ACCESS'
message'Unauthorized access'
identifier'errors.E_SIMPLE_UNAUTHORIZED_ACCESS'

Content Negotiation

SimpleAuthException implements a self-handling handle() method that inspects the request's Accept header using ctx.request.accepts(['html', 'application/vnd.api+json', 'json']) and formats the 401 response accordingly:

{
  "errors": [
    {
      "message": "Unauthorized access"
    }
  ]
}

Internationalization (@adonisjs/i18n)

If @adonisjs/i18n is installed and configured in your application (attaching ctx.i18n to the HttpContext), SimpleAuthException automatically looks up the translation key errors.E_SIMPLE_UNAUTHORIZED_ACCESS via ctx.i18n.t().

Add the translation key to your language files to return localized error messages:

{
  "E_SIMPLE_UNAUTHORIZED_ACCESS": "Unauthorized access. Please provide a valid API key."
}

If ctx.i18n is not present or the translation key is not defined, the exception falls back to 'Unauthorized access'.

Custom Exception Handling

If you want to intercept SimpleAuthException globally and return a custom payload, you can check for SimpleAuthException inside your application's HttpExceptionHandler (app/exceptions/handler.ts):

app/exceptions/handler.ts
import type { HttpContext } from '@adonisjs/core/http';
import { ExceptionHandler } from '@adonisjs/core/http';
import { SimpleAuthException } from '@eienjs/adonisjs-simple-auth';

export default class HttpExceptionHandler extends ExceptionHandler {
  async handle(error: unknown, ctx: HttpContext) {
    if (error instanceof SimpleAuthException) {
      return ctx.response.status(error.status).send({
        success: false,
        error: error.code,
        message: error.getResponseMessage(error, ctx),
      });
    }

    return super.handle(error, ctx);
  }
}