0Pricing
Flask Academy · Aula

Registre funções errorhandler

Personalize as respostas para 404 e 500.

Registre funções errorhandler é uma aula grátis de Flask Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Flask Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Flask Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Beyond the Default Page

Flask shows a plain error page out of the box. You can replace it by registering your own errorhandler for any status code.

The errorhandler Decorator

You attach a function to a code with a decorator. This handler runs whenever that error happens anywhere in your app.

@app.errorhandler(404)
def not_found(e):
    return "Nothing here", 404

Return a Tuple

A handler returns a body and a status code, just like a view. The status code keeps the response honest about what failed.

return "Not found", 404

The Error Argument

Each handler receives the error object as its argument. You can read its description or code to shape your reply.

def not_found(e):
    return str(e.description), 404

Handling 500 Errors

Unexpected crashes become a 500. Register a handler so users see a calm message instead of a raw stack trace.

@app.errorhandler(500)
def boom(e):
    return "Server error", 500

Render a Template Instead

Most apps return a styled page on error. Just call render_template in the handler and pass the status code along.

return render_template("404.html"), 404

Return JSON for APIs

An API should answer errors in JSON, not HTML. Use jsonify so clients can parse the failure cleanly.

return jsonify(error="Not found"), 404

Handlers Catch abort Too

Calling abort with a code triggers the matching handler. So one errorhandler covers both crashes and your own aborts.

Handle Exception Classes

You can register a handler by exception type, not just by number. Pass an exception class to catch a whole family at once.

@app.errorhandler(ValueError)
def bad(e):
    return "Bad value", 400

App-Wide vs Blueprint

Handlers on app apply everywhere, while a blueprint can scope its own. This lets each part of a big app fail its own way.

Why Custom Handlers Help

Consistent error pages keep your brand and your API tidy. A central handler means you fix the message in one place.

Quick Check

Spot the decorator that customizes a missing-page response.

Recap

You can now register errorhandler functions, read the error object, and return HTML or JSON with the right code. Great progress!

Perguntas Frequentes

A aula “Registre funções errorhandler” é grátis?

Sim — o texto completo de “Registre funções errorhandler” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Flask Academy, atualize para CoddyKit PRO. O curso de Flask Academy inclui 4 aulas no total.

O que vou aprender em “Registre funções errorhandler”?

Personalize as respostas para 404 e 500. Você pratica Flask Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Flask Academy?

Nenhuma experiência prévia é necessária. Flask Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Registre funções errorhandler”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Flask Academy?

Sim. Cada aula de Flask Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. abort e códigos de erro HTTP
  2. Registre funções errorhandler
  3. Lance classes de exceção personalizadas
  4. Envelopes uniformes de erro JSON
← Voltar para Flask Academy