Modern APIs with FastAPI and Python Transcripts
Chapter: Error handling and performance
Lecture: Concept: Converting errors to responses
0:00 We saw a simple mistakes or missing data or things like that,
0:04 like misspelling a city would result in a server crash. That was not ideal,
0:09 To be honest. The problem was we were just saying,
0:11 Look, if we got some bad error from the API,
0:13 crash. Well, so it did.
0:16 Instead, what we probably want to do is add ways to convert exceptions and errors
0:21 on the server over too FastAPI responses that communicate that back to the caller.
0:26 So here we've upgraded our weather method to say "try to call the get report" and
0:32 then we're gonna wait it, and if that all works, great,
0:35 just return it. However, if there's a validation error,
0:38 this is the error class we created that has the error message and status code.
0:42 So in one place, we could say this is like a bad data error 400,
0:45 this is like 404, things not found type of error.
0:49 We could have created different types of errors,
0:52 right? Like a validation error versus a not found error and so on.
0:56 But remember, we're getting a bunch of different responses from the open weather map and
1:00 we have to convert those status codes back over,
1:03 and it just seemed like a big hassle.
1:04 So let's just pass the error message and the status code around.
1:08 So this is like the well known error, this first except block. We're gonna return a response
1:12 with the message and the status code.
1:14 But there's also the possibility that it wasn't a validation error.
1:17 Like maybe the network socket couldn't be opened or some random thing that we tried to
1:21 do really did crash, right.
1:23 Like we tried to parse some
1:24 JSON and they didn't give us JSON,
1:26 I don't know. So we also wanna have an except block that is a general error
1:30 handler. And here we're just gonna say,
1:32 uh, that kind of really did crash, status code 500. And lets us do some
1:37 logging. Now we're just printing it here,
1:38 But obviously you would save that in a more durable place,
1:41 maybe a database, maybe just some,
1:43 you know, write it to a log or something like that.
1:45 But we probably wanna have this general exception as X at the very end,
1:49 you know, just in case,
1:50 because in production, it's gonna happen somewhere.
1:53 Making these changes with more validation and the error handling and so on has made our
1:58 service much more durable and really,
2:01 really feels a lot more professional.
2:02 We're starting to get a lot of information communicated back instead of just "sorry that didn't
2:07 work", crash boom. Really, really important to put this little bit of polish on our API.