Custom Exceptions

Custom exceptions for Django models

Define Custom Exceptions

# errors.py

class Error(Exception):
    pass
    

class ExceedsLimit(Error):
    pass
    
class InvalidAmount(Error):
    def __init__(self, amount):
        self.amount = amount
    
    def __str__(self):
        return f'Invalid Amount: {self.amount}'


class InsufficientFunds(Error):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        
    def __str__(self):
        return f'amount={self.amount}, current balance: {self.balance}'

We define a base Error class the inherits from Exception. This is something we found very useful and we use it a lot. A base error class allows us to catch all errors coming from a certain module:

Handling Errors

Define a custom errors to catch both transport and remote application errors. There are two types of errors we need to handle"

  • HTTP errors such as connection errors, timeout or connection refused.

  • Remote payment errors such as refusal or stolen card.

Last updated