PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How do I integrate custom exception handling with the FastAPI exception handling?

 August 04, 2022     exception, fastapi, python-3.x     No comments   

Issue

Pythom 3.9 FastAPI 0.78.0

I have a custom function that I use for application exception handling. When requests run into internal logic problems, i.e I want to send an HTTP response of 400 for some reason, I call a utility function.

@staticmethod
def raise_error(error: str, code: int) -> None:
    logger.error(error)
    raise HTTPException(status_code=code, detail=error)

Not a fan of this approach. So I look at

from fastapi import FastAPI, HTTPException, status
from fastapi.respones import JSONResponse

class ExceptionCustom(HTTPException):
    pass


def exception_404_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": "404"})


app.add_exception_handler(ExceptionCustom, exception_404_handler)

The problem I run into with the above approach is the inability to pass in the message as an argument.

Any thoughts on the whole topic?


Solution

Your custom exception can have any custom attributes that you want. Let's say you write it this way:

class ExceptionCustom(HTTPException):
    pass 

in your custom handler, you can do something like

def exception_404_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": exc.detail})

Then, all you need to do is to raise the exception this way:

raise ExceptionCustom(status_code=404, detail='error message')

Note that you are creating a handler for this specific ExceptionCustom. If all you need is the message, you can write something more generic:

class MyHTTPException(HTTPException):
    pass
def my_http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=exc.status_code, content={"message": exc.detail})
app.add_exception_handler(MyHTTPException, my_http_exception_handler)

This way you can raise any exception, with any status code and any message and have the message in your JSON response.

There's a detailed explanation on FastAPI docs



Answered By - Thiago Salvatore
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing