Custom error handler: request.endpoint is None

I am using CustomExceptionHandler in Sanic and logging errors on console by using:

class CustomExceptionHandler(ErrorHandler):

    def default(self, request, exception):
        response = None

        if isinstance(exception, (SanicException, MethodNotSupported, NotFound,
                                  Unauthorized, Forbidden, RequestTimeout, PayloadTooLarge)):
            logger.info("Handled exception {}, for method {}".format(
                exception.__class__.__name__, request.endpoint))
            response = get_error_body_response(exception.args[0], exception.status_code)
        return response

After upgrading to Sanic 21.3.2, I am not getting the request.endpoint value, it is always None for some reason

This is how I am creating my route:

basic = Blueprint('basic_blueprint', version=4)

@basic.route('/hello/<name:string>', methods=['GET'], name='hello')

I also tried using:

basic = Blueprint('basic_blueprint', version=4)

@basic.get('/hello/<name:string>', name='hello')

:thinking:

I might need some more info on how this is working. Perhaps the exception is happening outside your route handler?

from sanic import Blueprint, Sanic
from sanic.handlers import ErrorHandler
from sanic.log import logger


class CustomExceptionHandler(ErrorHandler):
    def default(self, request, exception):
        logger.info(
            "Handled exception {}, for method {}".format(
                exception.__class__.__name__, request.endpoint
            )
        )

        return super().default(request=request, exception=exception)


app = Sanic(__name__, error_handler=CustomExceptionHandler())

basic = Blueprint("basic_blueprint", version=4)


@basic.get("/")
def bar(req):
    raise Exception("...")


app.blueprint(basic)
app.run(port=8888, debug=True)

When I hit the endpoint, it logs as expected.

[2021-03-23 12:53:31 +0200] [648522] [INFO] Handled exception Exception, for method __main__.basic_blueprint.bar
[2021-03-23 12:53:31 +0200] [648522] [ERROR] Exception occurred while handling uri: 'http://localhost:8888/v4'
Traceback (most recent call last):
  File "/home/adam/Projects/Sanic/sanic/sanic/app.py", line 722, in handle_request
    response = handler(request, **kwargs)
  File "/tmp/p.py", line 24, in bar
    raise Exception("...")
Exception: ...

On a side note, request.endpoint is being deprecated in favor of request.name.

Found the issue, I was trying to call a route that is not present in my app. Raising exceptions from the route that exists works fine.

I will change it to request.name

And thank you for such a quick response.

1 Like