Exception handling in Web API

后端 未结 3 1150
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 08:54

In my Web API project, I created sub projects (class libraries) where I handle actual data handling operations. My backend database is DocumentDB.

My question is how

3条回答
  •  误落风尘
    2021-01-12 09:08

    The error handling depends on your logic and how your API respond to its consumers.

    Basically, you have to use HTTP Status Codes according to the type of error.

    In your data access and business layer methods, you can depend on the return type. For example, in all methods that queries the database, if the object is not there, you can return NULL, and in your web API, if the method returns NULL, then simply return NotFound() which will respond to the client with a 404.

    As for the exceptions:

    You can use Error Codes in your business and data access layer and check for these codes in your web API actions. Then return a suitable status code accordingly. Ex: return a status code of 500 if there has been a connection issue to the database, or return a 400 (Bad Request) if the user didn't provide all required action parameters in the correct format.

    In case of any other exception that you didn't catch, you can go with the global exception handler described by @Win

提交回复
热议问题