11

Catching Internal Server Error 500 Efficiently in Deta Micro!

 2 years ago
source link: https://gist.github.com/jnsougata/e835e6c914278853af35331b28bdf163
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

image

Are you tired of getting above message?

Micro's builtin debugger might annoy you sometimes with not traceback about what caused the Internal Server Error. Let's catch internal server error just by using a simple middleware. Note this will only work with Starlette & FastAPI. Let's say you have the following app:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

For some reason this causes Internal Server Error but micros's debugger is unable to output any error log! Here comes the role of a middleware which can catch the exception and send response accordingly.

warning Caution warning

This method is not suitable for production as it might leak sensitive information with traceback. Thanks to a discord friend baller#0001 for pointing it out.

Creating Exception Handling Middleware

import traceback
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import JSONResponse


async def catch_exceptions_middleware(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception as e:
        err = traceback.format_exception(type(e), e, e.__traceback__)
        return JSONResponse(content={"traceback": err}, status_code=500)

Adding middleware to the app

import traceback
from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import JSONResponse


async def catch_exceptions_middleware(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception as e:
        err = traceback.format_exception(type(e), e, e.__traceback__)
        return JSONResponse(content={"traceback": err}, status_code=500)

app = FastAPI()
app.middleware('http')(catch_exceptions_middleware)

@app.get("/")
async def root():
    return {"message": "Hello World"}

You are all set

Now you will be able to receive detailed tracebacks like the following:

image

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK