I am using the following code to show a common error page whenever an exception is thrown.
I have two questions. First question is how to configure it in a way to support all types of the exceptions?
The other question is how to register the type of exception thrown in database for future maintenance? I know I can save them into database after catching them but how about exceptions such as antlr versioning exception that are not catch by back-end and will be thrown through front-end ?
<global-results>
<result name="cuerror">error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="cuserror"/>
</global-exception-mappings>
If you want to catch all errors try java.lang.Throwable exception.
For database exception I suggest you declare new exceptions so catch database exceptions and throw you defined new exceptions, there you can decide the type of exception by new exception which is thrown
I do not see any reason for this, I think the database exception and its message is sufficient for maintenance.
Related
I do not quite understand and I could not find the answer to the question bothering me. Can the try..except block catch and pass the sub-procedure exception?
Let's say that i have code:
try
ProcedureA;
except
on E : Exception do
...
end;
and code for ProcedureA
procedure ProcedureA;
begin
SubProcedureA;
SubProcedureB;
SubProcedureC;
...
end;
If SubProcedureB raises exception, will the exception be handled at the main ProcedureA level? Will SubProcedureC be performed? Will the exception be forwarded to procedure A unchanged? Or maybe there is a restriction on sub-procedures, for example, Sub-sub-sub-procedure will no longer pass an exception to the higher-level procedure?
Thank you for the information and I apologize if this is a beginner question (which I am). :)
If SubProcedureB raises exception, will the exception be handled at the main ProcedureA level?
Yes. When an exception is raised, it propagates up the call stack until a matching handler catches it. If no handler catches it, then the process will usually terminate.
Will SubProcedureC be performed?
Usually no, however on Windows at least, it is possible (but not with Delphi's except syntax) for an exception handler to instruct the system to return back to the original call site that raised the exception. This is useful in rare cases where an exception handler can actually fix the condition that caused the exception to be raised in the first place, allowing execution to continue from where it left off. But again, this is very rare.
Will the exception be forwarded to procedure A unchanged?
Usually yes. There is only 1 Exception object in memory, and it is passed to each exception handler on the call stack until a matching handler is found. That being said, it is possible for an exception handler to catch an exception, modify it (it is just an object in memory, after all), and then re-raise it to continue the search up the call stack for another handler. That is not the case in your example, but it is allowed.
Or maybe there is a restriction on sub-procedures, for example, Sub-sub-sub-procedure will no longer pass an exception to the higher-level procedure?
There is no such restriction.
Try except block catches the exception at any level. The exception is thrown up until it is processed.
Top level is Application.OnException event.
So, the question is in the title.
The only one thought that comes in mind why we need to introduce custom Exception class is to pass additional info with exception raising.
Any additional reasons?
There are several reasons why you may want to create custom exceptions:
Add custom logic to an exception, to simplify the interaction with the exception itself. ActiveRecord::RecordInvalid is an example: the message is built from the actual record errors, and a reference to the record itself is stored in the exception.
Differentiate errors to improve error handling. Having different error types allows you to specifically rescue only certain types of errors, and not all the errors. You can also have different rescue blocks depending on the error type.
Re-raising typed errors. This is very important for libraries that internally relies on other libraries. A good practice of software composition is that library A uses B internally, whatever error B raises should be wrapped into an A error to make sure that the users of A don't have to deal with B directly.
In general, providing custom errors enhances the error handling experience. A good resource to learn more about errors is Avdi's book Exceptional Ruby. Highly recommended.
To avoid the Pokemon exception handling (Gotta' catch them all) anti-pattern it is better to raise your own exception types.
When using a library for example you should get meaningful error types - for example AuthorizationError or TimeOutError - it lets programmers deal with exceptions by type instead of matching the error message or adding a clunky system of numeric codes which does not really belong in an object oriented language.
I am using Grails 2.3 to create a REST API, and I want a better way to handle rendering error responses as a JSON response. What is have currently is a package of exceptions that all have a toJSON method. So all my controller methods wrap everything in the same try/catch blocks and render any error responses the same way.
What I really want is to have an uncaught exception handler that does all this without having to wrap everything in try/catch. So if there's an uncaught exception, it'll automatically convert the exception into JSON, set the appropriate status code, and write and flush the response.
Given all that, here's the actual question:
So the first question is: is this a dumb idea?
Since Grails handles all the thread pooling, I think I would need to register my handler at the beginning of every api call. Should I do this in the beforeInterceptor closure of each controller?
Also, how would I be able to access the response object from my handler in order to be able to write the proper response?
Even if someone could point me to the relevant grails classes in the docs, that would be a big help. I searched and could not find the classes where grails does this to see if I can use their existing classes instead of writing my own.
http://grails.org/doc/latest/guide/theWebLayer.html#mappingToResponseCodes might help. In essence, mapped custom ErrorController could render uncaught exceptions to JSON,
class MyJSONErrorController {
def handleError() {
def exception = request.exception
// perform desired processing to handle the exception
render exception as JSON
}
}
Doing beforeInterceptor or try catch block in each controller seems overwhelming. As Spring framework advocated, only catch exceptions that you need handle specifically than common errors.
I have an exception which its raise command causes stack overflow. I read this article in order to know what should I do: http://www.debuggingexperts.com/modeling-exception-handling
What I understood is the exception 0xc0000025 means attempt to catch an exception which is forbidden to be caught (EXCEPTION_NONCONTINUABLE_EXCEPTION). Am I right?
If so, I wish to know what cause the exception to be defined as non-continuable. The exception is defined in Pascal and derived from Exception object.
In addition, I failed to found where this exception is handled, and added by myself a try-catch block. The exception caught successfully. Why?
EDIT
I want to explain the specific situation I need help:
There is a C++ code which calls Pascal code, which has the exception definition, and raise command happens in it.
Before I put the try-catch block in the C++ code, the raise in Pascal causes 1000 times exception of EXCEPTION_NONCONTINUABLE_EXCEPTION until stack overflowed.
After I added the try-catch block in the C++ code, the raise in Pascal code returned to the catch block in the C++ code.
Now I have 2 questions:
Why process didn't stop on the first NONCONTINUABLE exception?
Why the catch block in C++ code didn't cause this exception?
You are correct that EXCEPTION_NONCONTINUABLE_EXCEPTION means the program attempted to continue from an exception that isn't continuable. However, it's not possible to define such an exception in Delphi, so the source of your problem is elsewhere.
Consider debugging the creation, raising, catching, and destruction of your custom exception type. If there are external libraries involved in your program, particularly any written in something other than Delphi, make sure they either know what to do with external exceptions, or are shielded entirely from exceptions.
Could anyone please guide me on what's the best practice to handle exception in ASP.NET MVC?
Controller?
Model?
Model (Contains EF logics i.e. save, update etc) throw any exception and catch in Controller?
In any method or block of code where you may expect specific exceptions (interacting with a database or an external service which may or may not not be available, etc.) wrap that code in a Try/Catch to catch the specific exception(s) in question. You'd want to know exactly what kind of exceptions occurred to handle them properly. (Naturally, use a Finally block to dispose of any open resources.) How to properly handle them is up to you and how you want your application to behave.
You should definitely have a global exception handling to catch anything unexpected which falls through the cracks. At no point should an unhandled exception bubble up to the user. The global exception handler should just present the user with a friendly error message and should log the exception and notify you of what happened. Generally, a good goal is to identify the exception and add error handling code to catch it in its localized state before it bubbles up to global. The goal, over time, should be to have as few global exceptions as possible and to have any potentially-exception-generating code have its own error handling to guard against those cases.
An example of the latter could be something as simple as a particular method receiving null arguments that you want to check for before using those arguments. One thing you want to avoid, however, is using exception handling for logic flow. For example...
Let's say you have a method which takes a custom object as an argument:
public MyMethod(MyObject obj)
{
// ...
}
Your original code assumes that obj will always have a value. However, after some time of production use, you discover that obj is sometimes null and that it's throwing a NullReferenceException from within that method, which is being caught by the global exception handler.
You may be tempted to just wrap the code in MyMethod in its own Try/Catch block to catch that exception. This isn't necessarily a good idea (though there may be cases where it is). Instead, you'd want to check for null at the start of the method:
public MyMethod(MyObject obj)
{
if (obj == null) throw new ArgumentNullException("obj can not be NULL");
// ...
}
This encapsulates the method better and allows it to throw controlled exceptions. Exceptions aren't bad things, only unexpected exceptions. Note that the above will still throw the exception which will still bubble up to the global handler. Thus, it's also a good idea to wrap the calls to this method in a Try/Catch block in order to catch the ArgumentNullException and handle it accordingly. Perhaps the code which calls this method can fix the null reference and try again, perhaps it can try something else, etc. You still don't want it to bubble up to the global handler if possible, since this has become an "expected" exception and can be handled accordingly.
Naturally, you still want to avoid the throwing/catching of the expected exceptions in the above example, so similar checks for null should happen before calling the method so that the method isn't even called.
Maybe if the object is null you can directly present the user with an error message and log the error and notify you of as much information about the state of things as possible so that you can research why it's null and fix it. Maybe being null is a perfectly acceptable state of that object at that time according to the logic of the application. If so, check if it's null and don't bother calling the method. Just carry on as normal.
It's a lot of error-checking and handling code, but that's a good thing.
Edit: Another thing to note about exception handling is that you should catch the exception only if you can actually handle it at that time. If the method can't handle it internally, let the exception bubble up from the method to the calling method, and so on. Thus, the only exceptions which should reach the global handler are exceptions which you can't actually handle anywhere in the code (which is why it's a good goal to fix and prevent global exceptions).
"Handle" in this case would mean being able to actually do something about it. Maybe that something is to just log it and carry on, maybe that something is to perform some specific logic, etc. But to catch, log, and re-throw is bad design. If you can't recover from the exception, let it bubble up.
The best way is to catch the exception globally, log it using Elmah. Otherwise you will have to put all your exceptions in your every controller code and that would be a lot of repetition especially for CRUD operations