locked
.NET Core getting a meaningful error message to the client RRS feed

  • Question

  • User-1699898665 posted

    Hi,

    I'm struggling to see how to get a useful error message to a client.  Based on the tutorial I've created this error controller:

        [ApiController]
        public class ErrorController : ControllerBase
        {
            [Route("/error")]
            public IActionResult Error([FromServices] IWebHostEnvironment webHostEnvironment) //=> Problem();
            {
                var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
    
                if (webHostEnvironment.EnvironmentName.ToLower() == "development")
                {
                    return Problem(
                        statusCode: 500,
                        detail: context.Error.StackTrace, 
                        title: context.Error.Message);
    
                }
                else
                {
                    return Problem(
                        statusCode: 500,
                        title: context.Error.Message);
                }
    
            }
        }
    

    And created an exception to try it out:

            List<OrganisationList> IDataService.GetOrganisationList()
            {
                List<OrganisationList> resultList = null;
    
                    resultList = dbConnection.Query<OrganisationList>("dbo.uspContactsGetOrganisationList", commandType: CommandType.StoredProcedure).ToList();
    
                throw new Exception("Hi, I'm a random error");
    
                return resultList;
            }

    And this is the Javascript handling the subsequent response:

        function getItems() {
            fetch(uri)
                .then(function (response) {
                    console.log(response); 
    
                    if (!response.ok) {
                        throw new Error("HTTP status " + response.status);
                    }
                    return response.json();
                })
                .then(data => {
    
                    _displayItems(data);
                })
                .catch(error => {
    
                    window.alert("An error occurred, please see the console for details.");
    
                    console.error('Error in getItems : ', error)
                });
        }

    But when I look at the console, the response data has the generic "Internal error" message:

    Response
    ​
    body: ReadableStream { locked: false }
    ​
    bodyUsed: false
    ​
    headers: Headers {  }
    ​
    ok: false
    ​
    redirected: false
    ​
    status: 500
    ​
    statusText: "Internal Server Error"
    ​
    type: "cors"
    ​
    url: "http://localhost/testcoreapi2020/test/organisation"
    ​
    <prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }

    How can I get my error message, whatever that is, to the client?

    Kind regards, Paul

    Tuesday, August 18, 2020 4:38 PM

Answers

  • User1120430333 posted

    You don't need an error controller in a WebAPI solution. You need a Error Filter class in the Core WebAPI solution.

    https://stackify.com/csharp-catch-all-exceptions/

    The example Github solution is using a Global Exception Handler in the WebAPI solution that catches all exceptions, logs them and sends the exception back to the ASP.NET MVC client that detects that there is not a HTTP 200 in the ServiceLayer returned from the WebAPI and throws an exception sending information sent back from the WebAPI so that it's logged on the client-side and a friendly message shown to the user.  

    https://github.com/darnold924/PublishingCompany/tree/master/WebAPI

    HTH

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 18, 2020 4:57 PM

All replies

  • User1120430333 posted

    You don't need an error controller in a WebAPI solution. You need a Error Filter class in the Core WebAPI solution.

    https://stackify.com/csharp-catch-all-exceptions/

    The example Github solution is using a Global Exception Handler in the WebAPI solution that catches all exceptions, logs them and sends the exception back to the ASP.NET MVC client that detects that there is not a HTTP 200 in the ServiceLayer returned from the WebAPI and throws an exception sending information sent back from the WebAPI so that it's logged on the client-side and a friendly message shown to the user.  

    https://github.com/darnold924/PublishingCompany/tree/master/WebAPI

    HTH

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 18, 2020 4:57 PM
  • User-1699898665 posted

    Thanks DA924.  I will look into your solution in more detail, but after using Postman and seeing that the Problem response was being made, I investigated further and found out that the issue was simply that I didn't understand how and where to access the response body properly.  I now have this code at the client:

        function getItems() {
            fetch(uri)
                .then(response => response.json())
                .then(data => {
    
                    if (data.status == undefined) {
                        _displayItems(data);
                    }
                    else {
                        throw new Error(data.status + " " + data.title);
                    }
    
                })
                .catch(error => {
    
                    window.alert("An error occurred, please see the console for details.");
    
                    console.error('getItems : ', error)
                });
        }

    So by doing this little check I can determine if the response body is an Problem object or not and handle accordingly.

    Kind regards, Paul

    Wednesday, August 19, 2020 4:04 PM