---
title: "💭 Handling Errors - FastAPI"
description: "!https://fastapi.tiangolo.com/tutorial/handling-errors/"
date: 2024-04-30
published: true
tags:
  - webdev
  - fastapi
  - thought
template: link
---


<div class="embed-card embed-card-external">
  <a href="https://fastapi.tiangolo.com/tutorial/handling-errors/" class="embed-card-link" target="_blank" rel="noopener noreferrer">
    <div class="embed-card-image">
      <img src="https://fastapi.tiangolo.com/assets/images/social/tutorial/handling-errors.png" alt="Handling Errors - FastAPI — FastAPI framework, high performance, easy to learn, fast to code, ready for production" loading="lazy">
    </div>
    <div class="embed-card-content">
      <div class="embed-card-title">Handling Errors - FastAPI</div>
      <div class="embed-card-description">FastAPI framework, high performance, easy to learn, fast to code, ready for production</div>
      <div class="embed-card-meta">fastapi.tiangolo.com</div>
    </div>
  </a>
</div>


This page shows how to customize your fastapi errors.  I found this very useful to setup common templates so that I can return the same 404's both programatically and by default, so it all looks the same to the end user.


``` python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse


class UnicornException(Exception):
    def __init__(self, name: str):
        self.name = name


app = FastAPI()


@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=418,
        content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
    )


@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"unicorn_name": name}
```

---


This post sat in draft for months.  I stumbled upon it again and found great success returning good error messages based on user preferences.  the default remains json, but if a user requests `text/html` it will be an html response, and text for `application/rtf` or `text/plain`

!!! note

    This post is a <a href="/thoughts/" class="wikilink" data-title="Thoughts" data-description="These are generally my thoughts on a web page or some sort of url, except a rare few don&#39;t have a link. These are dual published off of my..." data-date="2024-04-01">thought</a>. It's a short note that I make
    about someone else's content online <a href="/tags/thoughts/" class="hashtag-tag" data-tag="thoughts" data-count=2 data-reading-time=3 data-reading-time-text="3 minutes">#thoughts</a>
