Stop Piston's error catching - python

I'm using Piston with Django. Anytime there's an error in my handler code, I get a simplified, text-only description of the error in my http response, which gives me much less information that Django does when it's reporting errors. How can I stop Piston catching errors in this way?

In your settings.py file, add PISTON_DISPLAY_ERRORS = False this will cause exceptions to be raised allowing them to be shown as expected in the Django debug error page when you are using DEBUG = True.
There are a few cases when the exception won't propagate properly. I've seen it happen when Piston says that the function definition doesn't match, but haven't looked to see why...

Maybe you could try to override Resource.error_handle, and instead of using the default implementation:
https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/resource.py#cl-248
just re-raise the original exception.

Related

Pyhon: A better way to run a function when an error occurs in the program?

I created a big program that does a lot of different stuff. In this program, I added some error management but I would like to add management for critical errors which should start the critical_error_function().
So basically, I've used :
try :
//some fabulous code
except :
critical error(error_type)
But I am here to ask if a better way to do this...
In Python exceptions are the intended way of error handling. Assuming you wrap your whole program in one try-except block, a better way would be to
only try-except-wrap the lines that can generate exceptions instead of your complete program
catch them with a specific exception such as ValueError or even your own custom exception instead of the blank except statement
handle them appropriately. Handling could mean skipping this value, logging the error or calling your critical_error_function.

How to change error and failure detection in pytest?

In pytest, I want to report all uncaught AssertionError exceptions as Failure and all other uncaught exceptions as Errors (instead of the default behavior of reporting all uncaught exceptions in setup method as Errors while all uncaught exceptions in test cases and UUT as Failure). I thought it could be done with pytest hooks. However, "passed", "skipped", and "failed" seem to be the only valid outcome values in TestReport object.
So,
Is it possible to add "error" as a valid outcome and let the rest of pytest do the appropriate reporting, i.e., display E/ERROR instead of F/FAILURE on console output?
If so, what would be the ideal part of the source to do this?
If we cannot add "error" as a valid outcome, then what would be the best way to inject this behavior?
[Self answer]
pytest-finer-verdicts plugin achieves this behavior :)

Custom Message on Runtime-Error

Is it possible to add a Custom Message globally on runtime-erros? I would like to have a time-stamp as this would help figuring out if a file eventually was written by that execution process.
Replacing sys.excepthook with an appropriate function will allow you to do whatever you like upon every occurrence of an uncaught exception.
Take a look at the Python docs (2, 3) on handling exceptions. You can catch the RuntimeError and print the original message along with a custom timestamp. For more information on accessing the stack trace and exception messages, check out this question.
Ignacio's solution is also great if you'd like to set the message globally.

What's the purpose of raising in error?

What's the point of using raise if it exits the program?
Wouldn't it be just as effective to allow the crash to happen?
If I leave out the try-except block, the function crashes when I divide by zero and displays the reason. Or is there some other use that I don't know about?
def div(x,y):
try:
return(x/y)
except ZeroDivisionError as problem:
raise (problem)
I your case effect would be the same. But you may want to perform some additional logic in case of error (cleanup etc.) and perhaps raise a different (perhaps custom) error instead of original system low-level one, like with a message "Incorrect data, please check your input". And this can be done catching the error and raising a different one.
There is no point (in this case) in using raise. Normally, you'd have some code in there to do "something else" - that could include outputting some more debug information, writing some log data out, retrying the operation with a different set of parameters, etc. etc. etc.
I'm not sure there's much value in your case, where when an exception occurs it just re-raises it - it seems like someone (perhaps) intended to write some sort of handling code there, but just never got around to it.
Some great examples of the use cases for exception handling are in the Python Exception Handling Wiki --> http://wiki.python.org/moin/HandlingExceptions
The reason to re-raise an exception is to allow whatever code is calling you the opportunity to handle it after you have done something to handle it yourself. For example, you have closed a file that you were using (because cleanliness is a virtue) but your code cannot continue.
If you are not going to do anything to handle the exception, then no, there is no reason to write an exception handler for it!
The correct way to re-raise an exception is to simply use raise without any arguments. This way, whoever catches the exception (or the user of the script, if nobody catches it) gets a correct stack trace that tells where the exception was originally raised.

Pyramid catch-all friendly exception handling

Is there a way that I can handle some sort of "catch-all" error handling in a Pyramid web app? I currently have implemented exception logging to a database (via the docs at http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/logging/sqlalchemy_logger.html) and I'll return messages to my views to put a "friendly" face on what happened.
But is there something I can implement that would show some sort of generic "Oops, you ran into a problem and we're looking into it" for anything else I'm not explicitly catching, and I could use the above error handler behind the scenes to log whatever to the database? Or, what sort of thing should I be looking for in searches?
Thanks,
edit, since I can't fit it all into a comment:
.
Thanks, that seems to be exactly what I'm looking for!
One thing I'm running into, I don't know if it's related or not....
So I'm implementing the SQL logger as above like so:
class SQLAlchemyHandler(logging.Handler):
# A very basic logger that commits a LogRecord to the SQL Db
def emit(self, record):
trace = None
exc = record.__dict__['exc_info']
if exc:
trace = traceback.format_exc(exc)
log = Log(
logger=record.__dict__['name'],
level=record.__dict__['levelname'],
trace=trace,
msg=record.__dict__['msg'],)
DBSession.add(log)
DBSession.flush()
#transaction.commit()
I had to take out the 'transaction.commit()' call and instead use .flush() because I was getting a SQLAlchemy DetachedInstanceError exception when using transaction. I think it's because I'm playing some games with passing a request to a helper function and that's where it seems to be throwing it. So it works by flushing the session. Buuuut, what happens is if I have a log.error() statement in my exception view, if an exception is actually thrown the view catches it (great!) but the log statement in the view doesn't get committed. The debugging logs in Pyramid show it being written, but never committed.
If I change the logging handler back to transaction.commit then the exceptions do get committed, but I'm back at my original problem. I think I need to focus back on what I'm doing in my helper function that's causing it in the first place, but I'm still learning SQLAlchemy in general, too. Sometimes it can be a little strange.
You can set up an exception view. For example:
#view_config(context=Exception)
def error_view(exc, request):
#log or do other stuff to exc...
return Response("Sorry there was an error")

Categories

Resources