Error Handling & i18n
When ctx.simpleAuth.authenticate() fails, it throws a SimpleAuthException. This exception is thrown in any of the following cases:
- The configured
apiKeyHeaderis missing from the request. - The header value in the request is empty or contains only whitespace.
- The configured
apiKeyValueinconfig/simpleauth.tsis empty or contains only whitespace. - The request header value does not match
apiKeyValue(compared using timing-safesafeEqual).
Exception Properties
SimpleAuthException extends @adonisjs/core/exceptions's Exception class with the following default properties:
| Property | Value |
|---|---|
status | 401 |
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"
}
]
}
{
"errors": [
{
"code": "E_SIMPLE_UNAUTHORIZED_ACCESS",
"title": "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."
}
{
"E_SIMPLE_UNAUTHORIZED_ACCESS": "Acceso no autorizado. Por favor proporcione una clave API válida."
}
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):
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);
}
}
