OxygenFramework / Oxygen.jl

💨 A breath of fresh air for programming web apps in Julia
https://oxygenframework.github.io/Oxygen.jl/
MIT License
383 stars 25 forks source link

Would graceful failing be possible? #151

Closed asjir closed 5 months ago

asjir commented 5 months ago

My server is expecting a JSON payload from Oxygen endpoint, when Oxygen server errors it doesn't return valid json leading to: SyntaxError: Unexpected token 'T', "The Server"... is not valid JSON

The best idea that comes to my mind right now is to implement a keyword argument to post get etc. handlers with an error callback. It would be passed the caught error as an argument, so I could return an error json from there.

For now I can just do try catch blocks but since the server already catches errors to print them it could also let me return some json then.

ndortega commented 5 months ago

Hi @asjir,

That's right, the default error catcher just returns a 500 with text at the moment. This was done to prevent server errors from leaking by default. Although, this behavior is completely optional and can be customized. You just need to turn off the default error handling and write your own error handling middleware.

Below is an example of how to do this:

https://github.com/ndortega/Oxygen.jl/blob/master/demo/errorhandling.jl

asjir commented 5 months ago

Thank you!! Here's what I got for my usecase:

errh(cb) = f -> req -> try
    f(req)
catch e
    cb(e)
end
@post ("/api") function (req)
    payload = json(req, MyStruct)
    (; data=process(payload)
    end |> errh(x -> (; error=string(x)))

and it seems good enough to me.