Ninja automatically catches the typical exceptions raised by views and turns them into error objects to be returned by the view. In this lesson, you’ll learn how to define your own exceptions and override the defaults provided by Ninja.
00:12 The good news is Ninja tells you a fair amount about what went wrong. The bad news is it might not tell you where you expect. At least, it wasn’t where I expected the first time I wrote an API with this library.
00:25 The other bit of bad news is decorators can be a bit challenging to debug. This isn’t Ninja’s fault. Their choice of using decorators makes it simpler to write your code, but due to how decorators are called, you often can’t just put a breakpoint on them.
00:40 This isn’t a problem if things are running smoothly, but there are days where smoothly feels very far away. Let’s go look at some errors. No new apps this time. I’m just going to hit our existing ones.
01:42 It would be nice for more of the info that shows in the response to also be in the console. You get the 404, but if you’ve got a complex view, you may not be sure where that’s happening inside the view.
03:00 That’s a security problem on the server side though, which means the debug log. It would be nice to differentiate between the two causes. The first case is missing a cookie, whereas the second has the right header but the wrong password. This is a bit of a rougher edge, but now that you know where to look for it, it isn’t too bad.
Ninja is catching and handling the standard Django exceptions and then running code to return a response. You can take advantage of this by using Ninja’s
HTTPError exception, which allows you to raise any kind of HTTP error, explicitly setting the status code. You can also write your own exception handlers or use that same process to override Ninja’s built-in handlers if you prefer. Let’s add a new app and visit the Citadel.
Ninja provides a general
HTTPError exception inside of its errors module. I’ve used it in this example to raise a 503. Note that I’m creating a third Ninja object, which I’ve named
citadel for this lesson. Inside the
conclave API endpoint, I raise a 503 error by using the
HTTPError exception and setting the status code and corresponding message.
You can also define your own exceptions. Here, I’ve created the
BookUnavailable exception. I register a custom exception handler by passing the
BookUnavailable error into the
.exception_handler() method on the
Using a similar registration mechanism, you can override Ninja’s default handlers. In order to do so, I’ll need the
HTTPResponse classes from Django’s
http module. Ninja already has something for the 404, but by calling the
exception_handler decorator, I can override it with my own.
06:57 And I’ve been told to take the black. I must have done something naughty. There you go. Pull your t-shirt up to cover part of your face and grab a katana. You’re a Ninja now. The last lesson is next.
Become a Member to join the conversation.