TanStackT
TanStackโ€ข10mo agoโ€ข
2 replies
radical-lime

Centralized Error Handling and Middleware Errors

Hello, I'm coming from a Python/Flask background for backend development, and I am struggling in tanstack Start to handle errors in general.

In the flask world we can create something like this:

@errors.app_errorhandler(HTTPException)
def http_error(error: HTTPException):
    log_error(error)

    data = dict(
        code=error.code,
        message=error.name,
        description=error.description,
    )

    return data, error.code
    
@errors.app_errorhandler(Exception)
def other_exceptions(error: Exception):
    log_error(error)

    data = dict(
        code=InternalServerError.code,
        message=InternalServerError().name,
        description=InternalServerError.description,
    )

    return data, 500


This sets up different global error handlers for different types of Exceptions. When an error is raised, I can log it,
and a structured error response (code, message, description) is returned to the frontend.

I'm struggling to find an equivalent approach here. Specifically:

1. Global Error Handling: How can I implement centralized error handling, similar to Flask's @app_errorhandler?
or any other way to catch different type of errors for different displays.
2. Middleware Error Responses: In authentication middleware, if a user is unauthorized/forbidden, I want to return a 401 or 403 response.
Currently, it seems I'm limited to redirects or throwing 500 errors. It would be nice to be able to setup the HTTP status code directly.

Also on the frontend side I'm struggling to catch efficiently the errors...

Thanks to anyone who can help ๐Ÿ™‚
Was this page helpful?