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, like misspelling a city would result in a server crash. That was not ideal,
0:10 To be honest. The problem was we were just saying, Look, if we got some bad error from the API, crash. Well, so it did.
0:17 Instead, what we probably want to do is add ways to convert exceptions and errors
0:22 on the server over too FastAPI responses that communicate that back to the caller.
0:27 So here we've upgraded our weather method to say "try to call the get report" and then we're gonna wait it, and if that all works, great,
0:36 just return it. However, if there's a validation error, this is the error class we created that has the error message and status code.
0:43 So in one place, we could say this is like a bad data error 400, this is like 404, things not found type of error.
0:50 We could have created different types of errors, right? Like a validation error versus a not found error and so on.
0:57 But remember, we're getting a bunch of different responses from the open weather map and we have to convert those status codes back over,
1:04 and it just seemed like a big hassle. So let's just pass the error message and the status code around.
1:09 So this is like the well known error, this first except block. We're gonna return a response with the message and the status code.
1:15 But there's also the possibility that it wasn't a validation error.
1:18 Like maybe the network socket couldn't be opened or some random thing that we tried to do really did crash, right. Like we tried to parse some
1:25 JSON and they didn't give us JSON, I don't know. So we also wanna have an except block that is a general error handler. And here we're just gonna say,
1:33 uh, that kind of really did crash, status code 500. And lets us do some logging. Now we're just printing it here,
1:39 But obviously you would save that in a more durable place, maybe a database, maybe just some, you know, write it to a log or something like that.
1:46 But we probably wanna have this general exception as X at the very end, you know, just in case, because in production, it's gonna happen somewhere.
1:54 Making these changes with more validation and the error handling and so on has made our service much more durable and really,
2:02 really feels a lot more professional. We're starting to get a lot of information communicated back instead of just "sorry that didn't
2:08 work", crash boom. Really, really important to put this little bit of polish on our API.