locked
how to catch exception globally RRS feed

  • Question

  • User-590375999 posted

    Hi,

    I need to catch the exception globally in web api 2,

    how can i throw the exception from the helping classes?

    i am using vb.net language, i can't find any guide using vb.net and most of the methods not working in vb.net, showing errors if i convert the c# to vb.net code.

    Thursday, June 7, 2018 7:39 AM

Answers

  • User-369506445 posted

    hi sivapooja

    did you try my sample ?

    as far as i understood your mean , you want catch your error in your helpers class and custom it based on your needs and return to client

    if yes please follow below step:

    1- create a folder in your root called Filter

    2-create a class in Filter folder called MyExceptionFilterAttribute

    Imports System.Web.Http.Filters
    
    Public Class MyExceptionFilterAttribute
        Inherits ExceptionFilterAttribute
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            Dim ex = actionExecutedContext.Exception
    
            If (ex.Message.Equals("my Exception")) Then
                Throw New Exception("Generate your custom Exception")
            End If
    
            'Here log your exception'
        End Sub
    End Class

    3- in App_start folder in WebApiConfig file put below code :

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web.Http
    
    Public Module WebApiConfig
        Public Sub Register(ByVal config As HttpConfiguration)
            ' Web API configuration and services
    
            ' Web API routes
            config.MapHttpAttributeRoutes()
    
            config.Routes.MapHttpRoute(
                name:="DefaultApi",
                routeTemplate:="api/{controller}/{id}",
                defaults:=New With {.id = RouteParameter.Optional}
            )
    
    
            config.Filters.Add(New MyExceptionFilterAttribute())
        End Sub
    End Module

    4-create a class called HelperClass

    Public Class HelperClass
    
        Public Function dosomething() As Boolean
            Throw New Exception("my Exception")
        End Function
    End Class

    5-create a Api Controller called DefaultController

    Imports System.Net
    Imports System.Web.Http
    
    Namespace Controllers
        Public Class DefaultController
            Inherits ApiController
    
            ' GET: api/Default
            Public Function GetValues() As IEnumerable(Of String)
    
                Dim helper As New HelperClass()
                helper.dosomething()
    
                Return New String() {"value1", "value2"}
            End Function
    
        End Class
    End Namespace

    now run your project and fire your API address

    http://localhost:50702/api/Default

    now you can see your custom exception in browser

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 11, 2018 4:54 AM
  • User-369506445 posted

    yes you can

    for example in your attribute filter put below code :

    Imports System.Web.Http
    Imports System.Web.Http.Filters
    
    Public Class MyExceptionFilterAttribute
        Inherits ExceptionFilterAttribute
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            Dim ex = actionExecutedContext.Exception
    
            If (ex.Message.Equals("my Exception")) Then
    
                Throw New HttpResponseException(New Net.Http.HttpResponseMessage(Net.HttpStatusCode.InternalServerError) With
                                        {
                                        .Content = New Net.Http.StringContent("Internal server error")
                                        })
            End If
    
        End Sub
    End Class

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 11, 2018 6:36 AM

All replies

  • User-369506445 posted

    hi

    If you want to catch all exception into global method , please follow step by step below

    first create a filter class

    Imports System.Web.Http.Filters
      
    Public Class MyExceptionFilterAttribute 
    Inherits ExceptionFilterAttribute
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            Dim ex = actionExecutedContext.Exception
             'Here log your exception'
        End Sub
    End Class

    then add it into WebApiConfig file in App_start folder

      config.Filters.Add(new MyExceptionFilterAttribute())

    now create a API action and throw an exception, and put a break point into MyExceptionFilterAttribute  class

    you can see after each exception be fire your OnException method in MyExceptionFilterAttribute   class

    Thursday, June 7, 2018 8:04 AM
  • User-590375999 posted

    h,

    how to throw the exception to the client with error code and message?

    Thursday, June 7, 2018 8:39 AM
  • User-369506445 posted

    try below code in your API action

      throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, 
    "this item does not exist"))

    Thursday, June 7, 2018 8:44 AM
  • User753101303 posted

    Hi,

    Depends on what happens but usually you don't want to show exceptions that should be solved on your side. For example if the model doesn't validate per your rule you can send back error messages as it should be fixed from the client side but usually you don't want to send exception details if the issue is on your side as for a broken db connection or whatever...

    Edit: BTW I would even start at an even higher level such as Application_Error if not AppDomain?UnhandledException (for example if you have code in Application_Start that fails).

    Thursday, June 7, 2018 11:14 AM
  • User-590375999 posted

    Hi,

    i can't throw exception from the helper class files.

    1. i need to catch the exception at one place and send custom error code and message to the customer

    or 

        2. how to throw the exception from the helper class. call from controller methods.

    Monday, June 11, 2018 1:54 AM
  • User1120430333 posted

    Hi,

    i can't throw exception from the helper class files.

    1. i need to catch the exception at one place and send custom error code and message to the customer

    or 

        2. how to throw the exception from the helper class. call from controller methods.

    Granted, the basecontroller is a MVC example, but you also have controllers in the WebAPI. So why can't  you have a basecontroller for WebAPI controllers where all WebAPI controllers are derived from the basecontoller. Any exception thrown in a controller or below the controller is caught by the basecontroller.

    https://www.code-sample.com/2014/08/base-controller-in-mvc-5.html

    Monday, June 11, 2018 3:45 AM
  • User-369506445 posted

    hi sivapooja

    did you try my sample ?

    as far as i understood your mean , you want catch your error in your helpers class and custom it based on your needs and return to client

    if yes please follow below step:

    1- create a folder in your root called Filter

    2-create a class in Filter folder called MyExceptionFilterAttribute

    Imports System.Web.Http.Filters
    
    Public Class MyExceptionFilterAttribute
        Inherits ExceptionFilterAttribute
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            Dim ex = actionExecutedContext.Exception
    
            If (ex.Message.Equals("my Exception")) Then
                Throw New Exception("Generate your custom Exception")
            End If
    
            'Here log your exception'
        End Sub
    End Class

    3- in App_start folder in WebApiConfig file put below code :

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web.Http
    
    Public Module WebApiConfig
        Public Sub Register(ByVal config As HttpConfiguration)
            ' Web API configuration and services
    
            ' Web API routes
            config.MapHttpAttributeRoutes()
    
            config.Routes.MapHttpRoute(
                name:="DefaultApi",
                routeTemplate:="api/{controller}/{id}",
                defaults:=New With {.id = RouteParameter.Optional}
            )
    
    
            config.Filters.Add(New MyExceptionFilterAttribute())
        End Sub
    End Module

    4-create a class called HelperClass

    Public Class HelperClass
    
        Public Function dosomething() As Boolean
            Throw New Exception("my Exception")
        End Function
    End Class

    5-create a Api Controller called DefaultController

    Imports System.Net
    Imports System.Web.Http
    
    Namespace Controllers
        Public Class DefaultController
            Inherits ApiController
    
            ' GET: api/Default
            Public Function GetValues() As IEnumerable(Of String)
    
                Dim helper As New HelperClass()
                helper.dosomething()
    
                Return New String() {"value1", "value2"}
            End Function
    
        End Class
    End Namespace

    now run your project and fire your API address

    http://localhost:50702/api/Default

    now you can see your custom exception in browser

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 11, 2018 4:54 AM
  • User-590375999 posted

    Hi Bakkhi,

    can throw the exception with status code from outside of controller method  like this?

    Throw New HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal server error"))

    Monday, June 11, 2018 6:20 AM
  • User-369506445 posted

    yes you can

    for example in your attribute filter put below code :

    Imports System.Web.Http
    Imports System.Web.Http.Filters
    
    Public Class MyExceptionFilterAttribute
        Inherits ExceptionFilterAttribute
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            Dim ex = actionExecutedContext.Exception
    
            If (ex.Message.Equals("my Exception")) Then
    
                Throw New HttpResponseException(New Net.Http.HttpResponseMessage(Net.HttpStatusCode.InternalServerError) With
                                        {
                                        .Content = New Net.Http.StringContent("Internal server error")
                                        })
            End If
    
        End Sub
    End Class

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 11, 2018 6:36 AM
  • User-590375999 posted

    Hi bakkhi,

    i am getting follow error on OnException method

    System.Web.Http.HttpResponseException
      HResult=0x80131500
      Message=Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.
      Source=MYAPP
      StackTrace:
       at MYAPP.MYAPPExceptionFilterAttribute.OnException(HttpActionExecutedContext actionExecutedContext) in C:\Users\######\Exception\MYAPPExceptionFilterAttribute.vb:line 7
       at System.Web.Http.Filters.ExceptionFilterAttribute.OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    

    Monday, June 11, 2018 7:08 AM
  • User-369506445 posted

    please put your code here

    Monday, June 11, 2018 7:12 AM
  • User-590375999 posted

    Hi,

    Public Class MYAPPExceptionFilterAttribute
        Inherits ExceptionFilterAttribute
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
         
            Throw New Http.HttpResponseException(New Net.Http.HttpResponseMessage(Net.HttpStatusCode.InternalServerError) With
                                        {
                                        .Content = New Net.Http.StringContent(actionExecutedContext.Exception.Message)
                                        })
    
        End Sub
    End Class

    Monday, June 11, 2018 7:23 AM
  • User-369506445 posted

    please try <g class="gr_ gr_12 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="12" data-gr-id="12">belw</g> code 

    Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            Dim ex = actionExecutedContext.Exception
    
    
    
            Dim response As New Net.Http.HttpResponseMessage(Net.HttpStatusCode.InternalServerError) With
                                        {
                                        .Content = New Net.Http.StringContent(actionExecutedContext.Exception.Message)
                                        }
    
            actionExecutedContext.Response = response
    
    
    
        End Sub

    Monday, June 11, 2018 7:39 AM
  • User-590375999 posted

    Hi,

    This will revert the changes? i read if we don't throw error the changes will not be reverted.

    Monday, June 11, 2018 7:54 AM
  • User-369506445 posted

    if you call your API on a client you can get below message

    your status code changed

    your message changed

    Monday, June 11, 2018 8:09 AM
  • User-590375999 posted

    Hi,

    This is like send response right? not throwing exception right?

    Monday, June 11, 2018 8:23 AM
  • User-590375999 posted

    Tested code does not return error message

    Monday, June 11, 2018 8:26 AM
  • User-369506445 posted

    here are two different ways,

    if you want to throw an exception, you have to use first sample code 

    if you want change response status code without exception, you have to use last sample code 

    Monday, June 11, 2018 8:46 AM