Flask: difference between #app.errorhandler(500) and #app.errorhandler(exception) - api

From my understanding, #app.errorhandler(500) changes the default error for unhandled errors, while #app.errorhandler(exception) catches all errors (except ones already specified with a handler). Doesn't that mean that both of these things achieve the same thing essentially? is there really a difference

#app.errorhandler(500) would handle errors stemming from a page that returns a HTTP status code of 500. Whereas #app.errorhandler(exception) is more broad and can be used for global exception handling. For example if your code raises an OSError exception, this is where the exception shall be handled (unless the offending code is covered by its own try/catch block).
So it can be convenient for example to use #app.errorhandler(404) to customize your 404 Not found page and use #app.errorhandler(exception) all along for the more serious Python exceptions.

Related

when it is correct purpose of exceptions

I am studying OOP, and I did not understood the concept of exception.
What are the correct uses of exceptions?
Why use exceptions when you already know a possible exception?
For example, I have seen a code sample where the programmer needed to access a file, and had an exception in case the file does not exist. Something like "catch(fileDoesNotExist e)".
Why not use an if to verify before take the action? And use exception only for not known issues, for logging or error messages.
The idea behind the concept of exception was to decouple the error handling code from the "normal" behaviour flow control. That lets to manage/handle the exception further up the call stack.
Historically, with structured language, error handling code (file opening error,...) was mixed within the "business" application code. It was also painful to improve the code in order to manage new error codes.
What are the correct uses of exceptions?
If it is not normal that your file doesn't exist or cannot be opened => it is considered as an exceptional situation => exception => exception handler
Why use exceptions when you already know a possible exception?
To decouple the business application code from the error handling. That eases source code readibility and maintenance.
Exception:
Exception is that interrupt(break) the normal flow of the program.It's thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc
In java there are mainly two types of exception that checked and unchecked.Other than Error is there
Hierarchy of Exception classes in Java
Why use exceptions when you already know a possible exception?
basically exception handling use to mainly,we assuming in that our particular code will occur some(NullPointerException,ArrayIndexOutOfBoundsException etc..)exception.If we not Handle that,program will break.Actually that Exception it may or may not will happen.But so we need to handle normal flow of the program it occurred or not.Otherwise after that particular code section not executing.

ServerXMLHTTP fails on unresolvable ul

We are using the MSXML2.ServerXMLHTTP60Class to make HTTP requests. Usually this works fine, but on some occasions when the url cannot be resolved, the send method fails. In this case an exception is thrown.
The problem is that we program in Microsoft Dynamcs NAV C/AL code. This language does not support error trapping (try catch).
Does anybody know if there is some setting in the ServerXMLHTTP60Class that prevents the send method from failing?
Note: the send method fails, so checking the response status is not an option.
Thank you!
Depend your on version of Nav you have different ways to handle exeptions.
In Nav 2016 there will be try function
In previous versions you should use if codeunit.run then syntax to catch the exception and getlasterrortext to get error message.
For more information read Vjeco
Another option to avoid unhandled exceptions is to write a wrapper class around ServerXMLHTTP60Class that will catch all exceptions and handle them in the way you like.

Handling pgPL/SQL exceptions From QtSQL

Short and simple:
How to catch pgPL/SQL exceptions with QtSQL?
I haven't found any example or info at the docs.
More details:
I'm developing the front end for a system with Qt 5.3. The database perform some validation at some of the inputs and raise custom exceptions when something is invalid. What I want is to be able to handle these exceptions at he front end code, showing appropriate messages to the user.
EDIT:
I have tried to use the QSqlError class. Although it gave me the exception, it gave me too much data which will need to be parsed to be useful. Is there a way to get the exception raised without parsing the messages?

Preventing Exceptions without Stack Frames with Error Exception Handler and Shutdown Sequences

I've run over a somewhat little problem over the week. The error message upfront this is about:
[30-Dec-2012 15:19:32] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0
I think it is because my error handler (see below for details) is turning any error into an exception. I might should prevent that in case there is no stack frame.
Is there an easy way to find out if there is any stack frame or not in PHP?
Details:
On one of my websites I've got an error handler running that is turning every error into an exception, the common ErrorException to be precise.
I introduced it some time ago because the site is mainly legacy code and I wanted to have any issue result in an exception I can finally "catch" in a streamlined fashion an exception handler and give the request a stop.
I put this into class of it's own, the handler is registered and also in parallel an output buffer is opened to catch the output up until the exception is thrown. Basically code like this:
// register output buffering
$r = ob_start(array($this, 'handleBuffer'));
// register error handler
$this->_originalErrorHandler = set_error_handler(array($this, 'handleError'));
// register exception handler
$this->_originalExceptionHandler = set_exception_handler(array($this, 'handleException'));
This worked all fine and dandy until I decided to add another output buffering class into the mix. Just one that catches as well all output and then can do some "post production" on the website, including checking for HTML problems (yes, it's all a bit legacy so actually this is a bit duck-taped, I know). That also worked very fine btw. however not when I made a mistake in the new component:
[30-Dec-2012 15:19:32] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0
This is basically my problem. Is there an easy way to prevent getting these errors? I somewhat know why the error is given but I'm not so entirely sure so it's hard for me to really circumvent the problem. I tried to release the new output buffer before the script enters the new shutdown phase because I thought this would cause this. But this didn't make it.
Your problem indicates that you are using an EOL (End Of Life) version of PHP (specifically PHP < 5.3.0), which means it's no longer supported. This issue comes from throwing an exception where no strack frame exists and as such the old engine did not know how to handle those exceptions properly.
This can be due to a couple of different reasons. Some of the most common ones are as follows:
You threw an exception from inside an error handler or exception handler.
You threw an exception from inside a destructor.
You threw an exception from inside a callback (like an output buffering callback function).
Here's an example that demonstrates your problem under some of those circumstances...
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
function myExceptionHandler($exception) {
echo "We got an exception with message: '{$exception->getMessage()}'";
}
function myCallBack($contents) {
trigger_error('ohnoes!'); // You can't throw an error from the output buffer callback function in older versions of PHP < 5.3
}
class Foo {
public function __destruct() {
trigger_error('ohnoes!'); // You can't throw an error from a destructor in older versions of PHP < 5.3
}
}
set_error_handler('myErrorHandler');
set_exception_handler('myExceptionHandler');
The above code would cause you to see the fatal error you described here...
ob_start("myCallBack");
... and here...
$foo = new foo;
This problem has been fixed in PHP >= 5.3.0 so you should not see this issue if you were using the most current version of PHP.
The simplest fix is to upgrade your PHP. If that is not an option you must consider these facts that you can not throw exceptions where PHP does not expect them to be thrown (in callback functions, error handlers, exceptions handlers, etc... -- which are actually all considered to be callbacks to PHP).
The other thing is you should not be turning every error into an exception in this way. If what you are doing is as the code I supplied demonstrates (i.e. throwing an exception from inside the error handler -- thus turning every error into an exception) then you are going to cause yourself a lot of pain and with virtually no benefit. PHP errors are not meant to be handled. They are meant to inform the client of a problem (the client being the person writing the PHP code), or potential problem. Handling the error itself is not as simple as turning every error into an exception and then handling that exception, because not every error should be exceptional. For instance, E_NOTICE level errors have no place in exception handling. They are primarily used to notify you of a potential for a bug, not that there is necessarily something buggy with your code and not to mention that most of them can't even be handled easily in user-space code (they mostly require re-factoring the code itself). I strongly advice against this poor practice.

Handling controller missing controller parameters in turbogears 2

Suppose I have a controller method like so:
#expose()
def search(self, title):
return dict()
Going to http://site/search/ will cause an exception to be thrown: TypeError: search() takes exactly 2 arguments (1 given).
The error is logical, but I'd rather handle it more gracefully. Is using *args or **kwargs the only way to avoid an error that I don't even seem to be able to catch?
EDIT: I guess I could always use title=None, but too much of that could get ugly...
Anyway, is there a way to catch the exception and/or handle argument mismatches more gracefully?
Thanks
The exception thrown at you for specifying an "incompatible" controller method signature only happens in debug / development mode.
You dont need to handle it more gracefully in a production environment, because once you disable development mode, controller methods send an HTTP 500 Error when they lack essential parameters.
You might want to consider the respective settings in your development.ini:
# WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT*
# Debug mode will enable the interactive debugging tool, allowing ANYONE to
# execute malicious code after an exception is raised.
set debug = false
I hope this was your question.
In the case that you still want the controller do its work, even though its lacks important parameters, you must define default values, else the controller cannot do its work properly anyway.
The question you better ask yourself is: Do you simply want a nicer error message, or do you want the controller to be able to do its task. In the latter case, specifying default parameters is best practise, *args and **kwargs for each method just so the customer doesnt get an error is a very ugly hack in my option.
If you want to change the display of these errors refer to /controllers/error.py
Hope this helped,
Tom