Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug (500) Internal Server Error on Python Waitress server?

I'm using Python and Flask, served by Waitress, to host a POST API. I'm calling the API from a C# program that posts data and gets a string response. At least 95% of the time, it works fine, but sometimes the C# program reports an error: (500) Internal Server Error.

There is no further description of the error or why it occurs. The only clue is that it usually happens in clusters -- when the error occurs once, it likely occurs several times in a row. Without any intervention, it then goes back to running normally.

Since the error is so rare, it is hard to troubleshoot. Any ideas as to how to debug or get more information? Is there error handling I can do from either the C# side or the Flask/Waitress side?

like image 850
user3450049 Avatar asked Sep 22 '19 13:09

user3450049


People also ask

How does Python handle 500 internal server error?

Make sure debug mode is off, then try again. Here is a comment directly from the code itself: Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used.

How do you fix 500 Internal server error There is a problem with the resource you are looking for and it Cannot be displayed?

There is a problem with the resource you are looking for, and it cannot be displayed. The first solution to a 500 internal server error is to refresh the page. If the error persists, you may try clearing the cookies, deactivating faulty plugins or themes, fixing the . htaccess file, or contacting your hosting provider.


1 Answers

Flask supports registering error handlers. Defining error handlers enables customizing the server error logs as well as returning more meaningful information to the client.

Example

import logging
import traceback

from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException


app = Flask(__name__)
logger = logging.getLogger()

@app.errorhandler(HTTPException)
def handle_http_exception(error):
    error_dict = {
        'code': error.code,
        'description': error.description,
        'stack_trace': traceback.format_exc() 
    }
    log_msg = f"HTTPException {error_dict.code}, Description: {error_dict.description}, Stack trace: {error_dict.stack_trace}"
    logger.log(msg=log_msg)
    response = jsonify(error_dict)
    response.status_code = error.code
    return response
like image 69
Christopher Peisert Avatar answered Oct 10 '22 12:10

Christopher Peisert