Closed kennedymwavu closed 9 months ago
When an error occurs, it would be useful if it is passed to the handler. The handler can then choose what to do with the error (in most cases log it).
Currently, if I want to pass the error to the handler, I have to do a tryCatch() on the route and pass the error via res:
tryCatch()
res
app <- Ambiorix$new() app$get("/", \(req, res) { res$send("Hello, World!") }) # simulate error (object 'Pikachu' is not defined) app$get("/whoami", \(req, res) { tryCatch( expr = { res$send(Pikachu) }, error = \(err) { # pass error via res: res$error <- err # force error: stop() } ) }) app$error <- \(req, res) { # retrieve error from res: err <- res$error # print the error: err_msg <- conditionMessage(err) cli::cli_alert_danger("Error: {err_msg}") res$status <- 500L res$send("Uhhmmm... Looks like there's an error from our side :(") } app$start(port = 8000L, open = FALSE)
To avoid having to do unnecessary tryCatch()s on every route, we could do this instead (similar to express js):
app <- Ambiorix$new() app$get("/", \(req, res) { res$send("Hello, World!") }) # simulate error (object 'Pikachu' is not defined) app$get("/whoami", \(req, res) { res$send(Pikachu) }) error_handler <- \(req, res, err = NULL) { if (!is.null(err)) { # print/handle the error here: err_msg <- conditionMessage(err) cli::cli_alert_danger("Error: {err_msg}") } # response to client: res$status <- 500L res$send("Uhhmmm... Looks like there's an error from our side :(") } app$error <- error_handler app$start(port = 8000L, open = FALSE)
Still making myself familiar with the code base but I believe what I suggested can be done in these 3 sections:
return(private$.routes[[i]]$error(request, res, response))
return(self$error(request, res, response))
private$.routes[[i]]$error(request, res, error)
I can make a pull request if need be.
Ah yes you're correct, it should really have the error passed to it.
Thank you for the fix 60508af. It is working great!
Description
When an error occurs, it would be useful if it is passed to the handler. The handler can then choose what to do with the error (in most cases log it).
Currently, if I want to pass the error to the handler, I have to do a
tryCatch()
on the route and pass the error viares
:Suggestion
To avoid having to do unnecessary
tryCatch()
s on every route, we could do this instead (similar to express js):Hints
Still making myself familiar with the code base but I believe what I suggested can be done in these 3 sections:
I can make a pull request if need be.