client_python icon indicating copy to clipboard operation
client_python copied to clipboard

401 response increases counter http_requests_total{status="5xx"}

Open gionapaolini opened this issue 4 years ago • 0 comments

I have a FastApi application with a middleware to have a small level of security:

@app.middleware("http")
async def machine_key_validation(request: Request, call_next):
    valid = False //always false for the sake of this example
    if(not valid):
        raise HTTPException(status_code=401, detail="Not authenticated")
    return await call_next(request)

I just noticed that when it throws the 401 http exception, the http_requests_total{status="5xx"} counter gets increased, instead of http_requests_total{status="4xx"}

To give the full context, I also have changed the exception handlers so that I could return a custom message:

@app.exception_handler(HTTPException)
def http_exception_handler(request: Request, exc: HTTPException):
    return error_handler(request, exc)

@app.exception_handler(Exception)
def internal_server_error_handler(request: Request, exc: Exception):
    return error_handler(request, exc)

def error_handler(request: Request, exc: Exception):
    status_code = getattr(exc, "status_code", 500)
    exception_content = getattr(exc, "detail","Oops! Something went wrong on our side...")
    trace_id = getattr(request.state, "trace_id", None)
    if(trace_id): 
        span_context = SpanContext(trace_id=trace_id, span_id=5213367945872657620,is_remote=True, trace_flags=TraceFlags(0x01))
        ctx = trace.set_span_in_context(NonRecordingSpan(span_context))
        trace_id = hex(trace_id)[2:]  

    with trace.get_tracer(__name__).start_as_current_span("error_span", context=ctx) as span:
        span.set_attribute("http.status_code",status_code)
        return JSONResponse(
            status_code=status_code,
            content={"detail": exception_content, "trace_id": trace_id},
        )

gionapaolini avatar Oct 04 '21 14:10 gionapaolini