Add OnError() Hook

This commit is contained in:
BONNAURE Olivier 2024-02-05 20:27:11 +01:00
parent d50064a779
commit 4c6e2ec6d9
3 changed files with 106 additions and 79 deletions

View file

@ -575,7 +575,11 @@ 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()
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.
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

View file

@ -456,6 +456,7 @@ static bool isexitingworker;
static bool hasonworkerstart;
static bool leakcrashreports;
static bool hasonhttprequest;
static bool hasonerror;
static bool ishandlingrequest;
static bool listeningonport443;
static bool hasonprocesscreate;
@ -3243,6 +3244,7 @@ static bool ShouldServeCrashReportDetails(void) {
static char *LuaOnHttpRequest(void) {
char *error;
const char *errormessage;
lua_State *L = GL;
effectivepath.p = url.path.p;
effectivepath.n = url.path.n;
@ -3251,12 +3253,32 @@ static char *LuaOnHttpRequest(void) {
if (LuaCallWithYield(L) == LUA_OK) {
return CommitOutput(GetLuaResponse());
} else {
LogLuaError("OnHttpRequest", lua_tostring(L, -1));
error = ServeErrorWithDetail(
500, "Internal Server Error",
ShouldServeCrashReportDetails() ? lua_tostring(L, -1) : NULL);
lua_pop(L, 1); // pop error
return error;
errormessage = lua_tostring(L, -1);
LogLuaError("OnHttpRequest", errormessage);
if (hasonerror) {
lua_pushstring(L, errormessage);
lua_setglobal(L, errormessage);
lua_settop(L, 0);
lua_getglobal(L, "OnError");
if (LuaCallWithYield(L) == LUA_OK) {
return CommitOutput(GetLuaResponse());
} else {
error = ServeErrorWithDetail(
500, "Internal Server Error",
ShouldServeCrashReportDetails() ? errormessage : NULL);
return error;
}
} else {
error = ServeErrorWithDetail(
500, "Internal Server Error",
ShouldServeCrashReportDetails() ? errormessage : NULL);
lua_pop(L, 1); // pop error
return error;
}
}
}
@ -5569,6 +5591,7 @@ static void LuaInit(void) {
}
if (LuaRunAsset("/.init.lua", true)) {
hasonhttprequest = IsHookDefined("OnHttpRequest");
hasonerror = IsHookDefined("OnError");
hasonclientconnection = IsHookDefined("OnClientConnection");
hasonprocesscreate = IsHookDefined("OnProcessCreate");
hasonprocessdestroy = IsHookDefined("OnProcessDestroy");