Error Handling
Introduction
Error and exception handling is already configured by Lunox. The app/Exceptions/Handler.ts
file is where all exceptions thrown by your application are reported and rendered to the user.
Configuration
By default, the APP_DEBUG
environment variable is set to true
, which is useful for local development where you can see detailed error information. However, in your production environment, this value should always be false
.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the app/Exceptions/Handler
class. This class contains a register
method where you can register custom exception reporting and rendering callbacks. Exception reporting is used to log exceptions. You can use the reportable
method to register a closure that should be executed when an exception of a given type needs to be reported.
import ApiException from "app/Exceptions/ApiException";
register() {
this.reportable(ApiException, (e) => {
if (e.status >= 500) {
console.log("API Error", e);
}
});
}
Ignoring Exceptions By Type
When building your application, there may be certain types of exceptions that you want to ignore and never report. Your application's exception handler contains a dontReport
property, which is initialized to an empty array. Any classes that you add to this property will never be reported, although they may still have custom rendering logic.
import InvalidOrderException from 'app/Exceptions/InvalidOrderException';
protected dontReport = [
InvalidOrderException
];
Behind the scenes, Lunox already ignores certain types of errors for you, such as exceptions resulting from 404 HTTP "not found" errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
You can register a custom rendering closure for exceptions of a given type. This can be done using the renderable
method of your exception handler. The closure should return an instance of HttpResponse
or ViewFactory
.
import { ValidationException } from "@lunoxjs/validation";
import { HttpException } from '@lunoxjs/core';
import { Response } from "@lunoxjs/core/facades";
register() {
this.renderable(ValidationException, (e, req) => {
if (req.wantsJson()) {
return Response.make(
{
message: e.message,
errors: e.errors(),
status: 422,
},
422
);
}
return back().withInput().with({
errors: e.errors(),
});
});
this.renderable(HttpException, (e, req) => {
if (req.wantsJson()) {
return Response.make(
{
message: e.message,
status: e.getStatusCode(),
},
e.getStatusCode()
);
}
return view("_error", { message: e.message, code: e.getStatusCode() });
});
}
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401), or even a developer-generated 500 error. To generate such a response from anywhere in your application, you can use the abort
helper.
abort(404);