diff --git a/tool/net/definitions.lua b/tool/net/definitions.lua index cc36cc4a4..aa9e830de 100644 --- a/tool/net/definitions.lua +++ b/tool/net/definitions.lua @@ -550,6 +550,17 @@ SPECIAL PATHS --- function OnHttpRequest() end +--- Hooks catch errors +--- +--- If this functiopn is defined in the global scope by your `/.init.lua` +--- then any errors occuring in the OnHttpRequest() hook will be catched. +--- You'll be able then to do whatever you need with the error status and +--- error message. +--- +---@param status uint16 +---@param message string +function OnError(status, message) end + --- Hooks client connection creation. --- --- If this function is defined it'll be called from the main process diff --git a/tool/net/help.txt b/tool/net/help.txt index fb09bcb96..9c3ae4a7d 100644 --- a/tool/net/help.txt +++ b/tool/net/help.txt @@ -575,11 +575,13 @@ HOOKS hand over control for all messages (with the exception of OPTIONS *). See functions like Route which asks redbean to do its default thing from the handler. - OnError() + + OnError(status:int, message:string) If this function is defined and if any errors occurs in - OnHttpRequest() then this method will be called instead of - displaying the default 500 page. Useful if you need to display - the error page using your specific code. + OnHttpRequest() then this method will be called instead of displaying + the default error page. Useful if you need to display the error page + using your specific code or send it to any tier service. + OnClientConnection(ip:int, port:int, serverip:int, serverport:int) → bool If this function is defined it'll be called from the main process each time redbean accepts a new client connection. If it returns diff --git a/tool/net/redbean.c b/tool/net/redbean.c index 55a24d8ee..6f75d04e0 100644 --- a/tool/net/redbean.c +++ b/tool/net/redbean.c @@ -3253,29 +3253,25 @@ static char *LuaOnHttpRequest(void) { if (LuaCallWithYield(L) == LUA_OK) { return CommitOutput(GetLuaResponse()); } else { - errormessage = lua_tostring(L, -1); - LogLuaError("OnHttpRequest", errormessage); + LogLuaError("OnHttpRequest", lua_tostring(L, -1)); if (hasonerror) { - lua_pushstring(L, errormessage); - lua_setglobal(L, errormessage); - - lua_settop(L, 0); lua_getglobal(L, "OnError"); - if (LuaCallWithYield(L) == LUA_OK) { + lua_pushinteger(L, 500); + lua_pushstring(L, errormessage); + if (LuaCallWithTrace(L, 2, 0, NULL) == LUA_OK) { return CommitOutput(GetLuaResponse()); } else { error = ServeErrorWithDetail( - 500, "Internal Server Error", - ShouldServeCrashReportDetails() ? errormessage : NULL); - + 500, "Internal Server Error!!", + ShouldServeCrashReportDetails() ? lua_tostring(L, -1) : NULL); + lua_pop(L, 1); // pop error return error; } } else { error = ServeErrorWithDetail( 500, "Internal Server Error", - ShouldServeCrashReportDetails() ? errormessage : NULL); - + ShouldServeCrashReportDetails() ? lua_tostring(L, -1) : NULL); lua_pop(L, 1); // pop error return error; }