Exceptions filters
In Nestipy, any unhandled exceptions within the application are processed by a built-in exceptions layer. If your application code does not handle an exception, this layer intercepts it and automatically returns a user-friendly response.
This is a example of using exception filter with Nestipy.
from typing import Any
from nestipy.common import ExceptionFilter, Catch, HttpException
from nestipy.core import ArgumentHost
@Catch()
class HttpExceptionFilter(ExceptionFilter):
async def catch(self, exception: HttpException, host: ArgumentHost) -> Any:
print('Catcher')
To catch specific exception we need to create class that extends HttpException.
import datetime
from typing import Any
from nestipy.common import ExceptionFilter, Catch, HttpStatus, HttpStatusMessages, HttpException,
from nestipy.core import ArgumentHost
class BadRequestException(HttpException):
def __init__(self):
super(self, ).__init__(HttpStatus.BAD_REQUEST, HttpStatusMessages.BAD_REQUEST)
@Catch(BadRequestException)
class BadRequestExceptionFilter(ExceptionFilter):
async def catch(self, exception: HttpException, host: ArgumentHost) -> Any:
response = host.get_response()
request = host.get_request()
status = exception.status_code
print('Catcher')
return await response.json({
'statusCode': status,
'timestamp': datetime.datetime.now().strftime("%d/%m/%Y, %H:%M:%S"),
'path': request.path,
})
Binding filters
Let's tie our new BadRequestExceptionFilter to the CatsController's create() method.
from nestipy.common import Controller, Post
from nestipy.common import UseFilters
@Controller('cats')
class CatsController:
@UseFilters(BadRequestExceptionFilter)
@Post()
async def create(self):
raise BadRequestException()
Apply on controller.
from nestipy.common import Controller, Post
from nestipy.common import UseFilters
@UseFilters(BadRequestExceptionFilter)
@Controller('cats')
class CatsController:
@Post()
async def create(self):
raise BadRequestException()
To create a global-scoped filter, you would do the following:
from nestipy.core.nestipy_factory import NestipyFactory
app = NestipyFactory.create(AppModule)
app.use_global_filters(BadRequestExceptionFilter)
Using it from provider.
from nestipy.common import Module, ModuleProviderDict
from nestipy.core.constant import AppKey
@Module(
providers=[
ModuleProviderDict(token=AppKey.APP_FILTER, use_class=BadRequestExceptionFilter)
]
)
class AppModule:
Support us
Nestipy is a project released under the MIT license, meaning it's open source and freely available for use and modification. Its development thrives with the generous contributions of these fantastic individuals.