Registre funciones errorhandler
Personalice las respuestas para 404 y 500.
Registre funciones errorhandler es una lección gratuita de Flask Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Flask Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Flask Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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", 404Return 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", 404The 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), 404Handling 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", 500Render 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"), 404Return 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"), 404Handlers 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", 400App-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!
Preguntas frecuentes
¿La lección «Registre funciones errorhandler» es gratis?
Sí — el texto completo de «Registre funciones errorhandler» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Flask Academy, actualiza a CoddyKit PRO. El curso de Flask Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Registre funciones errorhandler»?
Personalice las respuestas para 404 y 500. Practicas Flask Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Flask Academy?
No se requiere experiencia previa. Flask Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Registre funciones errorhandler»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Flask Academy?
Sí. Cada lección de Flask Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- abort y códigos de error HTTP
- Registre funciones errorhandler
- Lance clases de excepciones personalizadas
- Envoltorios de error JSON uniformes