In Total.js, you can define custom routes to handle errors like 404 Not Found
or 500 Internal Server Error
. This lets you display custom error messages and pages when something goes wrong in your app, improving user experience.
In this post, we'll explore how to define error routes for different HTTP status codes, set status codes using $.res.send()
, and customize error responses in a simple way.
The way you define error routes in Total.js v5 is similar to previous versions. You can use the ROUTE
function with an HTTP status code to specify what happens when an error occurs.
Here’s a simple example of how it works:
In Total.js, you can send a custom response with an error code using $.res.send(code, body)
. This method sets the HTTP status code and sends a response back to the user.
Here’s an example of handling a 404 Not Found
error:
This method uses the Response.send()
function, which works like this:
404
).text/html
or application/json
).You can define custom routes for various HTTP errors, such as 403 Forbidden
, 404 Not Found
, and 503 Service Unavailable
, using $.res.send()
:
While you can create custom routes for most errors, it’s not recommended to create a custom route for 500 Internal Server Error
. If there’s an error in the handler, it could cause an infinite loop, continuously triggering the error.
Let Total.js handle 500
errors automatically to avoid these risks.
You can customize and localize error messages using @(message)
for multi-language support. This is helpful if your app serves users in different languages.
Here’s an example of a localized 403 Forbidden
error:
The @(message)
syntax allows Total.js to translate the message based on the user’s language settings.
Here’s a full example showing how to handle multiple error routes in Total.js:
In this example:
403
, 404
, and 503
errors.$.res.send(code, body)
to set the HTTP status code and send a custom error message.403
handler uses @(message)
for localized error messages.Defining error routes in Total.js allows you to provide custom error messages and pages, improving user experience when things go wrong. Here’s a summary of what we covered:
ROUTE('#code', handler)
to handle errors like 403
, 404
, and 503
.$.res.send(code, body)
to set the HTTP status code and send a custom response.500 Internal Server Error
to prevent infinite loops.@(message)
to support multiple languages.By following these steps, you can make sure your application handles errors effectively while giving users clear and helpful information.