GitHub

Usage

Custom Error Pages

You can fully customize error pages by overriding them with your own.


Usage

You can register custom error pages from inside your controllers, routes, middlewares or everywhere radonis is available on the HttpContext by passing your custom error views to the withErrorPages method. Views get passed the error as a prop, which you can then use to display detailed information about the error.

// resources/views/InternalServerError.tsx
interface InternalServerErrorProps {
  error: unknown
}


function InternalServerError({ error }: InternalServerErrorProps) {
  return <div>Ooops: {error instanceof Error ? error.message : 'An unknown error occurred'}</div>
}


export { InternalServerError }

Middleware

Below is an example of a middleware that registers a custom error page for internal server errors.

// app/Middleware/ErrorPages.ts
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { InternalServerError } from '../../resources/views/InternalServerError.tsx'


export default class ErrorPagesMiddleware {
  public async handle(
    { radonis }: HttpContextContract,
    next: () => Promise<void>
  ) {
    radonis.withErrorPages({
      500: InternalServerError,
    })


    await next()
  }
}

Only errors thrown while rendering are catched by Radonis. Errors thrown in controllers must be handled by an ExceptionHandler separately.

// app/Exceptions/Handler.ts
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Logger from '@ioc:Adonis/Core/Logger'
import { InternalServerError } from '../../resources/views/InternalServerError.tsx'


export default class ExceptionHandler extends HttpExceptionHandler {
  constructor() {
    super(Logger)
  }


  public async handle(error: any, ctx: HttpContextContract) {
    if (ctx.request.accepts(['html']) && error.status === 500) {
      /**
       * Render error page
       */
      return ctx.radonis.render(InternalServerError, { error })
    }


    /**
     * Forward rest of the exceptions to the parent class
     */
    return super.handle(error, ctx)
  }
}
Previous
Page Head