Search Results

Search found 2244 results on 90 pages for 'exceptions'.

Page 9/90 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • ASP.net MVC [HandleError] not catching exceptions.

    - by Eric
    In two different application, one a custom the other the sample MVC application you get with a new VS2008 MVC project, [HandleError] is not catching exceptions. In the sample application I have: [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; throw new Exception(); return View(); } public ActionResult About() { return View(); } } which is just the default controller with an exception being thrown for testing. But it doesn't work. Instead of going to the default error.aspx page it shows the debug information in the browser. The problem first cropped up in a custom application I'm working on which led me to test it with the sample application. Thinking it had something to do with changes I made in the custom application, I left the sample application completely unchanged with the exception (yuck) of the throw in the index method. I'm stumped. What am I missing?

    Read the article

  • exceptions with python unicode encode/decode functions (why doesn't errors=ignore actually ignore th

    - by gatoatigrado
    Does anyone know why the string conversion functions throw exceptions when errors="ignore" is passed? How can I convert from regular Python string objects to unicode without errors being thrown? Thanks very much! python -c "import codecs; codecs.open('tmp', 'wb', encoding='utf8', errors='ignore').write('?????')" returns Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/codecs.py", line 686, in write return self.writer.write(data) File "/usr/lib/python2.6/codecs.py", line 351, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

    Read the article

  • How do I handle all the exceptions in a C# class where both ctor and finalizer throw exceptions?

    - by Frank
    How can I handle all exceptions for a class similar to the following under certain circumstances? class Test : IDisposable { public Test() { throw new Exception("Exception in ctor"); } public void Dispose() { throw new Exception("Exception in Dispose()"); } ~Test() { this.Dispose(); } } I tried this but it doesn't work: static void Main() { Test t = null; try { t = new Test(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } // t is still null } I have also tried to use "using" but it does not handle the exception thrown from ~Test(); static void Main() { try { using (Test t = new Test()) { } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } Any ideas how can I work around?

    Read the article

  • How convince other developers not to ignore Exceptions?

    - by Mnementh
    Recently I encountered a bug in an application I took over from another developer. I debugged for the reason and over an hour later I realized, that the problem wasn't the code producing the exception, but some code executed before this returning wrong data. If I dived into this, I encountered the following: try { ... } catch (XYException e){} If the Exception would have been propagated (a change I did), I would have found the reason for the bugs in a few minutes, as the stacktrace had pointed me to the problem. So how can I convince other developers to never catch and ignore exceptions in this way?

    Read the article

  • controlling if exceptions are swallowed by a static boolean

    - by sandis
    So we are a few guys developing this product that is communicating with a really unstable server. It often returns very strange and corrupt data. During testing we want the resulting crashes to be loud, so we discover them. But every other day we need to demonstrate our product for a potential customer. To the customer the errors will go undiscovered if we just swallow them. I am thinking about implementing something like this around all server communication to quickly switch between swallowing exceptions and crashing: try { apiCall(); } catch (Exception e) { if(!SWALLOW_EXCEPTION) { throw e; } } Is this an awesome idea, or can it be done in a better way?

    Read the article

  • Disabling Xdebug's dumping of caught exceptions

    - by nuqqsa
    By default Xdebug will dump any exception regardless of whether it is caught or not: try { throw new Exception(); } catch (Exception $e) { } echo 'life goes on'; With XDebug enabled and the default settings this piece of code will actually output something like the following (nicely formatted): ( ! ) Exception: in /test.php on line 3 Call Stack # Time Memory Function Location 1 0.0003 52596 {main}( ) ../test.php:0 life goes on Is it possible to disable this behaviour and have it dumping only the uncaught exceptions? Thanks in advance. UPDATE: I'm about to conclude that this is a bug, since xdebug.show_exception_trace is disabled by default yet it doesn't behave as expected (using Xdebug v2.0.5 with PHP 5.2.10 on Ubuntu 9.10).

    Read the article

  • JSF hiding exceptions?

    - by bshacklett
    I have a managed bean for a JSF page which is doing JPA calls in the constructor to populate fields in the bean. I'm having a bit of trouble with another call to persist an entity (to populate data for testing). I'm expecting it to throw some sort of exception since it's not working, but I'm not getting anything. Just of the heck of it I tried the following: Query newQuery = em.createQuery("Bad Syntax"); List newList = newQuery.getResultList(); I'd expect an IllegalArgumentException here since the query string is completely invalid, but the page still loads and I don't see any exceptions anywhere. Am I right in expecting this exception? If so, why am I not seeing it?

    Read the article

  • UnitTest ExpectedException with multiple Exceptions

    - by masterchris_99
    I want one TestMethod for multiple exceptions. The Problem ist that the Testmethod stops after the first thrown exception. I know that I can do something like that: try { sAbc.ToInteger(); Assert.Fail(); // If it gets to this line, no exception was thrown } catch (ArgumentException) { } But I want to use the following code-base: [TestMethod, ExpectedException(typeof(ArgumentException), "...")] public void StringToIntException() { sAbc.ToInteger(); // throws an exception and stops here sDecimal.ToInteger(); // throws theoretically a exception too... } And I don't want to create one testmethod for each possible exception like that: [TestMethod, ExpectedException(typeof(ArgumentException), "...")] public void StringToIntException() { sAbc.ToInteger(); } [TestMethod, ExpectedException(typeof(ArgumentException), "...")] public void StringToIntException() { sDecimal.ToInteger(); }

    Read the article

  • Exceptions and web services

    - by Schildmeijer
    Im using the standard java ws implementation shipped with e.g. java6 (javax.jws.*). I have the following: import javax.jws.*; @WebService(name="Widget") public interface Widget { @WebMethod public @WebResult String getGadget(@WebParam(name = "id") long id) throw MyOwnException; } Is this possible? Do I have to annotate MyOwnException with e.g the @WebFault annotation? During my initial tests I also noticed that, on the client side, the autogenerated MyOwnException was renamed to MyOwnException_Exception and wrapped the "original" MyOwnException. Or if this is a bad idea, are there any recommended Exceptions to throw from a webservice like this?

    Read the article

  • JavaScript try/catch: errors or exceptions?

    - by Josh
    OK. I may be splitting hairs here, but my code isn't consistent and I'd like to make it so. But before I do, I want to make sure I'm going the right way. In practice this doesn't matter, but this has been bothering me for a while so I figured I'd ask my peers... Every time I use a try... catch statement, in the catch block I always log a message to my internal console. However my log messages are not consistent. They either look like: catch(err) { DFTools.console.log("someMethod caught an error: ",err.message); ... or: catch(ex) { DFTools.console.log("someMethod caught an exception: ",ex.message); ... Obviously the code functions properly either way but it's starting to bother me that I sometimes refer to "errors" and sometimes to "exceptions". Like I said, maybe I'm splitting hairs but which is the proper terminology? "Exception", or "Error"?

    Read the article

  • Handling PHP exceptions with JQuery

    - by Itamar Bar-Lev
    Hello, I'm using JQuery to call a PHP function that returns a JSON string upon success or throws some exceptions. Currently I'm calling jQuery.parseJSON() on the response and if it fails I assume the response contains an exception string. $.ajax({ type: "POST", url: "something.php", success: function(response){ try { var json = jQuery.parseJSON(response); } catch (e) { alert(response); return -1; } // ... do stuff with json } Can anyone suggest a more elegant way to catch the exception? Many thanks, Itamar

    Read the article

  • Handling multiple exceptions

    - by the-banana-king
    Hi there, I have written a class which loads configuration objects of my application and keeps track of them so that I can easily write out changes or reload the whole configuration at once with a single method call. However, each configuration object might potentially throw an exception when doing IO, yet I do not want those errors to cancel the overall process so that the other objects are still given a chance to reload/write. Therefore I collect all exceptions which are thrown while iterating over the objects and store them in a super-exception, which is thrown after the loop, since each exception must still be handled and someone has to be notified of what exactly went wrong. However, that approach looks a bit odd to me. Someone out there with a cleaner solution? Here is some code of the mentioned class: public synchronized void store() throws MultipleCauseException { MultipleCauseException me = new MultipleCauseException("unable to store some resources"); for(Resource resource : this.resources.values()) { try { resource.store(); } catch(StoreException e) { me.addCause(e); } } if(me.hasCauses()) throw me; }

    Read the article

  • Handling Exceptions that happen in a asp.net MVC Controller Constructor

    - by Jason
    What's the best way to handle exceptions that happen from within a controller's constructor? All I can think of to do is use Application_OnError() or put a try/catch in my ControllerFactory. Neither of these solutions seem ideal. Application_OnError is to broad - I have some non-mvc content in the site that has its own error handling. Using a try/catch block seems kinda hacky. If I'm serving different content type -html/text/json/rss.... I would like to be able to handle the exception from within the action method instead of having to write all kinds of conditions to determine what kind of error message to serve. Am I missing something here, or has anyone else dealt with this?

    Read the article

  • .net Attributes that handle exceptions - usage on a property accessor

    - by Mr AH
    Hi, well I know from my asp.net mvc experience that you can have attributes that handle exceptions (HandleErrorAttribute). As far as I can tell the Controller class has some OnException event which may be integral to this behaviour. However, I want to do something similar in my own code: dream example: public String MyProperty { [ExceptionBehaviour(typeof(FormatException), MyExEnum.ClearValue)] set { _thing.prop = Convert.ToThing(value); } } .... The code above obviously makes very little sense, but is close to the kind of thing I wish to do. I want the attribute on the property set accessor to catch some type of exception and then deal with this in some custom way (or even just swallow it). Any ideas guys?

    Read the article

  • Displaying and capturing c# exceptions

    - by Frank Meulenaar
    I have a c# program which throws a NullReferenceException(). When I start this on my Vista machine, it gives the familiar screen "Foo has stopped working". I can easily click on 'details' to see what went wrong. On one XP machine there's no warning at all: the program just quits, and on another XP I get the "Foo has encountered a problem..." message. Is there a way I can change this (XP's) setting? Furthermore, I would like to have this error message written to a log file, so I can see what went wrong if somebody else uses my program. Is there a way I can send the uncaught exceptions to a file?

    Read the article

  • Correct Exceptions in C++

    - by Dr.Ackula
    I am just learning how to handle errors in my C++ code. I wrote this example that looks for a text file called some file, and if its not found will throw an exception. #include <iostream> #include <fstream> using namespace std; int main() { int array[90]; try { ifstream file; file.open("somefile.txt"); if(!file.good()) throw 56; } catch(int e) { cout<<"Error number "<<e<<endl; } return 0; } Now I have two questions. First I would like to know if I am using Exceptions correctly. Second, (assuming the first is true) what is the benefit to using them vs an If else statement?

    Read the article

  • [C++] Boost test: catch user defined exceptions

    - by user231536
    If I have user defined exceptions in my code, I can't get Boost test to consider them as failures. For example, BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(MyTest,1) BOOST_AUTO_TEST_CASE(MyTest) { // code which throws user defined exception, not derived from std::exception. } I get a generic message: Caught exception: .... unknown location(0):.... It does not recognize this error as a failure since it is not a std::exception. So it does not honor the expected_failures clause. How do I enforce that the piece of code should always throw an exception? THis seems to be a useful thing to want. In case future code changes cause the code to pass and the exception is not thrown, I want to know that.

    Read the article

  • How to send exceptions to exceptionController?

    - by ivar
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="mappedHandlers"> <set> <ref bean="exceptionController" /> </set> </property> <property name="defaultErrorView" value="tiles/content/error" /> </bean> I'm trying to send exceptions to a controller so I can create a redirect. If I comment out the mappedHandlers part then the error tile is displayed but it is only a tile. The rest of the tiles load normally. I need to make a redirect in the controller so I can show an error page not just an error tile. I can't find enough information or an example how the exception invokes some method in exceptionController.

    Read the article

  • @ExceptionHandler doesn't handle the thrown exceptions

    - by Javi
    Hello, I have a method in my controller which will handle the exceptions thrown by the application. So I have a method like this one. @Controller public class ExceptionController { @RequestMapping(value="/error") @ExceptionHandler(value={Exception.class, NullPointerException.class}) public String showError(Exception e, Model model){ return "tiles:error"; } } And to try I if it works I throw a NullPointerException in another method in other method controller: boolean a = true; if(a){ throw new NullPointerException(); } After the exception is thrown it is printed in the JSP, but it doesn't go throw my showError() method (I've set a breakpoint there and it never enters). showError() method will catch the exception and will show different error pages depending on the exception type (though now it always shows the same error page). If I go to the url /error it shows the error page so the showError() method is OK. I'm using Spring 3. What can be the problem? Thanks.

    Read the article

  • Are all of the Oracle exceptions named?

    - by John O
    In particular, I've been trying to find the name of the ORA-0955 to improve code readability. Currently I'm using the following: EXCEPTION WHEN OTHERS THEN IF SQLCODE = -00955 What I would prefer is something like: EXCEPTION WHEN OBJECT_EXISTS THEN This seems cleaner to me and I would prefer that. But I've looked in SYS.STANDARD, and it lists relatively few named exceptions. Online documentation seems to mirror what's in SYS.STANDARD. Is there another package to look in? Some other resource?

    Read the article

  • How can I handle this kind of exceptions (in Doctrine)

    - by ppavlovic
    Can you tell me how can I handle this kind of exceptions: Fatal error: Uncaught exception 'Doctrine_Connection_Exception' with message 'PDO Connection Error: SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading initial communication packet', system error: 110' in ... It happens when connection with MySQL is lost during query. I need to handle this exception so I can show 500 error page so the crawlers do not cache page, and to redirect user to appropriate "Try again" page. P.S. I have a lot's of code, so I can not go trough all code to put try/catch block. I need something simple and yet effective.

    Read the article

  • I set a global bug catcher in my application for unhandled exceptions and it is picking up all exceptions

    - by user1632018
    I am trying to figure out why this is happing. In my vb.net application I set a global handler in the ApplicationEvents.vb which I thought would only pick up any unhandled exceptions, although it is picking up every exception that happens in my application whether or not they are handled with try catch blocks. Here is my code in applicationevents Private Sub MyApplication_UnhandledException(ByVal _ sender As Object, ByVal e As _ Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) _ Handles Me.UnhandledException e.ExitApplication = _ MessageBox.Show(e.Exception.Message & _ vbCrLf & "The application has encountered a bug, would you like to Continue?", "An Error has occured.", _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Question) _ = DialogResult.No End Sub In the rest of my application I set normal try catch blocks like this: Try Catch ex as exception End Try Can anyone tell me why this is happening?

    Read the article

  • ASP.NET Web API Exception Handling

    - by Fredrik N
    When I talk about exceptions in my product team I often talk about two kind of exceptions, business and critical exceptions. Business exceptions are exceptions thrown based on “business rules”, for example if you aren’t allowed to do a purchase. Business exceptions in most case aren’t important to log into a log file, they can directly be shown to the user. An example of a business exception could be "DeniedToPurchaseException”, or some validation exceptions such as “FirstNameIsMissingException” etc. Critical Exceptions are all other kind of exceptions such as the SQL server is down etc. Those kind of exception message need to be logged and should not reach the user, because they can contain information that can be harmful if it reach out to wrong kind of users. I often distinguish business exceptions from critical exceptions by creating a base class called BusinessException, then in my error handling code I catch on the type BusinessException and all other exceptions will be handled as critical exceptions. This blog post will be about different ways to handle exceptions and how Business and Critical Exceptions could be handled. Web API and Exceptions the basics When an exception is thrown in a ApiController a response message will be returned with a status code set to 500 and a response formatted by the formatters based on the “Accept” or “Content-Type” HTTP header, for example JSON or XML. Here is an example:   public IEnumerable<string> Get() { throw new ApplicationException("Error!!!!!"); return new string[] { "value1", "value2" }; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The response message will be: HTTP/1.1 500 Internal Server Error Content-Length: 860 Content-Type: application/json; charset=utf-8 { "ExceptionType":"System.ApplicationException","Message":"Error!!!!!","StackTrace":" at ..."} .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   The stack trace will be returned to the client, this is because of making it easier to debug. Be careful so you don’t leak out some sensitive information to the client. So as long as you are developing your API, this is not harmful. In a production environment it can be better to log exceptions and return a user friendly exception instead of the original exception. There is a specific exception shipped with ASP.NET Web API that will not use the formatters based on the “Accept” or “Content-Type” HTTP header, it is the exception is the HttpResponseException class. Here is an example where the HttpReponseExcetpion is used: // GET api/values [ExceptionHandling] public IEnumerable<string> Get() { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); return new string[] { "value1", "value2" }; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The response will not contain any content, only header information and the status code based on the HttpStatusCode passed as an argument to the HttpResponseMessage. Because the HttpResponsException takes a HttpResponseMessage as an argument, we can give the response a content: public IEnumerable<string> Get() { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("My Error Message"), ReasonPhrase = "Critical Exception" }); return new string[] { "value1", "value2" }; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   The code above will have the following response:   HTTP/1.1 500 Critical Exception Content-Length: 5 Content-Type: text/plain; charset=utf-8 My Error Message .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The Content property of the HttpResponseMessage doesn’t need to be just plain text, it can also be other formats, for example JSON, XML etc. By using the HttpResponseException we can for example catch an exception and throw a user friendly exception instead: public IEnumerable<string> Get() { try { DoSomething(); return new string[] { "value1", "value2" }; } catch (Exception e) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An error occurred, please try again or contact the administrator."), ReasonPhrase = "Critical Exception" }); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Adding a try catch to every ApiController methods will only end in duplication of code, by using a custom ExceptionFilterAttribute or our own custom ApiController base class we can reduce code duplicationof code and also have a more general exception handler for our ApiControllers . By creating a custom ApiController’s and override the ExecuteAsync method, we can add a try catch around the base.ExecuteAsync method, but I prefer to skip the creation of a own custom ApiController, better to use a solution that require few files to be modified. The ExceptionFilterAttribute has a OnException method that we can override and add our exception handling. Here is an example: using System; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Filters; public class ExceptionHandlingAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is BusinessException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(context.Exception.Message), ReasonPhrase = "Exception" }); } //Log Critical errors Debug.WriteLine(context.Exception); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An error occurred, please try again or contact the administrator."), ReasonPhrase = "Critical Exception" }); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Note: Something to have in mind is that the ExceptionFilterAttribute will be ignored if the ApiController action method throws a HttpResponseException. The code above will always make sure a HttpResponseExceptions will be returned, it will also make sure the critical exceptions will show a more user friendly message. The OnException method can also be used to log exceptions. By using a ExceptionFilterAttribute the Get() method in the previous example can now look like this: public IEnumerable<string> Get() { DoSomething(); return new string[] { "value1", "value2" }; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } To use the an ExceptionFilterAttribute, we can for example add the ExceptionFilterAttribute to our ApiControllers methods or to the ApiController class definition, or register it globally for all ApiControllers. You can read more about is here. Note: If something goes wrong in the ExceptionFilterAttribute and an exception is thrown that is not of type HttpResponseException, a formatted exception will be thrown with stack trace etc to the client. How about using a custom IHttpActionInvoker? We can create our own IHTTPActionInvoker and add Exception handling to the invoker. The IHttpActionInvoker will be used to invoke the ApiController’s ExecuteAsync method. Here is an example where the default IHttpActionInvoker, ApiControllerActionInvoker, is used to add exception handling: public class MyApiControllerActionInvoker : ApiControllerActionInvoker { public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { var result = base.InvokeActionAsync(actionContext, cancellationToken); if (result.Exception != null && result.Exception.GetBaseException() != null) { var baseException = result.Exception.GetBaseException(); if (baseException is BusinessException) { return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(baseException.Message), ReasonPhrase = "Error" }); } else { //Log critical error Debug.WriteLine(baseException); return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(baseException.Message), ReasonPhrase = "Critical Error" }); } } return result; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } You can register the IHttpActionInvoker with your own IoC to resolve the MyApiContollerActionInvoker, or add it in the Global.asax: GlobalConfiguration.Configuration.Services.Remove(typeof(IHttpActionInvoker), GlobalConfiguration.Configuration.Services.GetActionInvoker()); GlobalConfiguration.Configuration.Services.Add(typeof(IHttpActionInvoker), new MyApiControllerActionInvoker()); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   How about using a Message Handler for Exception Handling? By creating a custom Message Handler, we can handle error after the ApiController and the ExceptionFilterAttribute is invoked and in that way create a global exception handler, BUT, the only thing we can take a look at is the HttpResponseMessage, we can’t add a try catch around the Message Handler’s SendAsync method. The last Message Handler that will be used in the Wep API pipe-line is the HttpControllerDispatcher and this Message Handler is added to the HttpServer in an early stage. The HttpControllerDispatcher will use the IHttpActionInvoker to invoke the ApiController method. The HttpControllerDipatcher has a try catch that will turn ALL exceptions into a HttpResponseMessage, so that is the reason why a try catch around the SendAsync in a custom Message Handler want help us. If we create our own Host for the Wep API we could create our own custom HttpControllerDispatcher and add or exception handler to that class, but that would be little tricky but is possible. We can in a Message Handler take a look at the HttpResponseMessage’s IsSuccessStatusCode property to see if the request has failed and if we throw the HttpResponseException in our ApiControllers, we could use the HttpResponseException and give it a Reason Phrase and use that to identify business exceptions or critical exceptions. I wouldn’t add an exception handler into a Message Handler, instead I should use the ExceptionFilterAttribute and register it globally for all ApiControllers. BUT, now to another interesting issue. What will happen if we have a Message Handler that throws an exception?  Those exceptions will not be catch and handled by the ExceptionFilterAttribute. I found a  bug in my previews blog post about “Log message Request and Response in ASP.NET WebAPI” in the MessageHandler I use to log incoming and outgoing messages. Here is the code from my blog before I fixed the bug:   public abstract class MessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId); var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri); var requestMessage = await request.Content.ReadAsByteArrayAsync(); await IncommingMessageAsync(corrId, requestInfo, requestMessage); var response = await base.SendAsync(request, cancellationToken); var responseMessage = await response.Content.ReadAsByteArrayAsync(); await OutgoingMessageAsync(corrId, requestInfo, responseMessage); return response; } protected abstract Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message); protected abstract Task OutgoingMessageAsync(string correlationId, string requestInfo, byte[] message); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   If a ApiController throws a HttpResponseException, the Content property of the HttpResponseMessage from the SendAsync will be NULL. So a null reference exception is thrown within the MessageHandler. The yellow screen of death will be returned to the client, and the content is HTML and the Http status code is 500. The bug in the MessageHandler was solved by adding a check against the HttpResponseMessage’s IsSuccessStatusCode property: public abstract class MessageHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId); var requestInfo = string.Format("{0} {1}", request.Method, request.RequestUri); var requestMessage = await request.Content.ReadAsByteArrayAsync(); await IncommingMessageAsync(corrId, requestInfo, requestMessage); var response = await base.SendAsync(request, cancellationToken); byte[] responseMessage; if (response.IsSuccessStatusCode) responseMessage = await response.Content.ReadAsByteArrayAsync(); else responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase); await OutgoingMessageAsync(corrId, requestInfo, responseMessage); return response; } protected abstract Task IncommingMessageAsync(string correlationId, string requestInfo, byte[] message); protected abstract Task OutgoingMessageAsync(string correlationId, string requestInfo, byte[] message); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } If we don’t handle the exceptions that can occur in a custom Message Handler, we can have a hard time to find the problem causing the exception. The savior in this case is the Global.asax’s Application_Error: protected void Application_Error() { var exception = Server.GetLastError(); Debug.WriteLine(exception); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } I would recommend you to add the Application_Error to the Global.asax and log all exceptions to make sure all kind of exception is handled. Summary There are different ways we could add Exception Handling to the Wep API, we can use a custom ApiController, ExceptionFilterAttribute, IHttpActionInvoker or Message Handler. The ExceptionFilterAttribute would be a good place to add a global exception handling, require very few modification, just register it globally for all ApiControllers, even the IHttpActionInvoker can be used to minimize the modifications of files. Adding the Application_Error to the global.asax is a good way to catch all unhandled exception that can occur, for example exception thrown in a Message Handler.   If you want to know when I have posted a blog post, you can follow me on twitter @fredrikn

    Read the article

  • What do these MS DTC Exceptions mean?

    - by David B
    I wrote a program to demonstrate the behavior of DTC timeouts with multiple threads. I'm getting several exceptions, seemingly at random. Are all of these simple Timeouts, or are some of them indicative of deeper problems (connection pool interactions, etc)? The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction. Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction. The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements. The operation is not valid for the state of the transaction. ExecuteReader requires an open and available Connection. The connection's current state is closed. Here's the data part of the code: using (DemoDataDataContext dc1 = new DemoDataDataContext(Conn1)) using (DemoDataDataContext dc2 = new DemoDataDataContext(Conn2)) { WriteMany(dc1, 100); //generate 100 records for insert WriteMany(dc2, 100000); //generate 100,000 records for insert Console.WriteLine("{0} : {1}", Name, " generated records for insert."); using (TransactionScope ts = new TransactionScope()) { dc1.SubmitChanges(); dc2.SubmitChanges(); ts.Complete(); } }

    Read the article

  • Handling mach exceptions in 64bit OS X application

    - by Brad S
    I have been able to register my own mach port to capture mach exceptions in my applications and it works beautifully when I target 32 bit. However when I target 64 bit, my exception handler catch_exception_raise() gets called but the array of exception codes that is passed to the handler are 32 bits wide. This is expected in a 32 bit build but not in 64 bit. In the case where I catch EXC_BAD_ACCESS the first code is the error number and the second code should be the address of the fault. Since the second code is 32 bits wide the high 32 bits of the 64 bit fault address is truncated. I found a flag in <mach/exception_types.h> I can pass in task_set_exception_ports() called MACH_EXCEPTION_CODES which from looking at the Darwin sources appears to control the size of the codes passed to the handler. It looks like it is meant to be ored with the behavior passed in to task_set_exception_ports(). However when I do this and trigger an exception, my mach port gets notified, I call exc_server() but my handler never gets called, and when the reply message is sent back to the kernel I get the default exception behavior. I am targeting the 10.6 SDK. I really wish apple would document this stuff better. Any one have any ideas?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >