-1

I'm trying to create Refit library for my APIs.

I wanted to throw ApiExeption whenever status code received is other than 200 and 207.

public interface IServiceAPIs{
     [Post("/api/users/register")]
     Task<HttpResponseMessage> PostData([Header]string auth,RegisterUserRequest registerUserRequest);
}

and in my implementation class:

try {
    var response = service.PostData(auth,registerUsers);
    if(!response.IsSuccessStatusCode){
        throw new ApiException(); // Here I'm not able to find how to throw this exception
    }
} catch(ApiException Ex) {
    log.write(ex);
}

How can I throw exception.?
Thanks in advance.

Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • You need to call the constructor `throw **new** ApiException()` (without the asterisks obviously) – MindSwipe Apr 08 '22 at 09:20
  • Edited question. As ApiException does not have constructor which takes 0 constructor. I'm not able to throw exception. – Suyog Arun Khachane Apr 08 '22 at 10:02
  • 2
    Looking more into the code of refit, I found [this](https://github.com/reactiveui/refit/blob/246ee8d9989c29092fdaba6821d5b3098a5ccf9e/Refit/ApiException.cs#L119), seems like you're supposed to use the `Create` method like `await ApiException.Create(...)` where `...` are your parameters – MindSwipe Apr 08 '22 at 10:08
  • This worked ApiException.Create() served my purpose. I'm able to get ApiException using above method. Thanks @MindSwipe – Suyog Arun Khachane Apr 08 '22 at 15:22

1 Answers1

0

I just came across the similar requirement and solution is quite simple. If you use refit on client side every BadRequest is caught/handled as ApiException by Refit.

All you have to do is return return BadRequest("exception message") if you want to throw an exception within somewhere your Service or Repository when not in control. Do that by Throw new Exception("") (Exception should be AggregateException, NullException etc. not directly System.Exception), then catch this exception in your control like below and return BadRequest, this will be returned as ApiException on the client side.

your controller endpoint body.

         try
            {
                
                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
Emil
  • 6,411
  • 7
  • 62
  • 112