Router - Error Handling
VkrunJS allows adding error-handling middleware to ensure that if any exception occurs in a synchronous route, the application doesn’t crash, and a standard error response is provided.
Implementing Error Handling Middleware
Add the error-handling middleware using app.error()
. This middleware takes four parameters: error
, req
, res
. VkrunJS automatically forwards captured errors from synchronous handlers to this middleware, allowing you to define a custom response.
Note: The error middleware does not capture errors in asynchronous handlers. For those cases, wrap the code in
try-catch
within the controller.
Example: Error Handling Middleware
import v from "vkrun"
// Define the error-handling middleware
const errorHandler = (error: any, req: v.Request, res: v.Response) => {
res.status(500).send("Internal Server Error")
}
const vkrun = v.App()
// Add the error middleware
vkrun.error(errorHandler)
// Route without internal error handling (synchronous)
vkrun.get("/example-a", (req: v.Request, res: v.Response) => {
throw new Error("Any Error") // Caught by the middleware
res.status(200).send("GET method route")
})
// Route with internal error handling (asynchronous)
vkrun.get("/example-b", async (req: v.Request, res: v.Response) => {
try {
await someAsyncOperation()
res.status(200).send("Async GET method route")
} catch (error) {
res.status(503).send("503 - Service Unavailable") // Necessary in asynchronous handlers
}
})
vkrun.server().listen(3000, () => {
console.log("Vkrun started on port 3000")
})
Key Points
- Middleware for General Error Handling in Synchronous Routes: In synchronous routes, the
errorHandler
middleware captures thrown errors, as seen in/example-a
, and returns a500
response. - Error Handling in Asynchronous Handlers: For asynchronous routes, like
/example-b
,try-catch
must be used directly in the controller, as the middleware won’t catch exceptions in asynchronous code. - Fallback with Middleware: For synchronous handlers, the error middleware acts as a fallback to ensure a consistent response and prevent the application from crashing.
Best Practice
Using try-catch
is always the best approach for handling errors, especially in asynchronous routes, as it ensures that all potential issues are managed within the controller, leading to a more predictable and resilient application behavior.
For more details on middleware, see the VkrunJS Middleware Documentation.