The moment the error occurs makes me confusing. What is this? Why my error handler doesn't work expectedly?

The error makes the Sanic server shut down silently.

Let’s look at an example code:

import datetimeimport sanic
@app.route("/", methods=["GET"])
async def idnex(request: Request):
now = datetime.datetime.utcnow()
data = {"status": "OK", "data": now}
try:
return sanic.response.json(body=res)
except Exception as e:
logger.exception(e)
return sanic.response.json(
body={"status": "Error", "data": ""}
)

The Python datetimeobject is not JSON serializable. That means we expect to get the {“status”: “Error”, “data”: “”} return body with the exception log: TypeError: Object of type datetime is not JSON serializable.

Actually, we will get nothing but a Segmentation fault (core dumped) console log (Even no console log if running in the container!).

Hope this post will help everyone who got the same bug and save some time. Cheers!

--

--