I am trying to use RemoteServerException in my code like this:
throw new RemoteServerException(response.StatusCode,response.IsSuccessStatusCode,newUri("http://localhost:5045/myapi"),null,content);
but it always throws 500 instead of response.StatusCode that I set. why?
because it shows remote api's response in it's body like this image:
Related
I get this error when using the CustomVisionPredictionClient like so:
var predictionApi = new CustomVisionPredictionClient()
{
ApiKey = _predictionKey,
Endpoint = "https://westeurope.api.cognitive.microsoft.com"
};
var result = await predictionApi.ClassifyImageAsync(project.Id, _modelName, imageData);
The project/project id is retrieved via the training API, on which I can call GetProjects() without a problem. It should be correct, if I change it to something wrong I get a "not found" exception.
_modelName is the published name of the iteration ("xxxRecognition", see screenshot below), it should also be correct, when I change it I get "not found".
imageData is just a FileStream from a PNG image.
The problem was that I created an "Object Detection" type project and tried to use it with ClassifyImage() which has to be used with "Classification" type projects. So I have to use DetectImage() instead. :)
There's two items to address here.
Your particular "Bad Request"
Your example, specifically, has one or more of these problems that you haven't really included.
The _modelName is malformed
The imageData is not formatted properly
Some configuration, likely of request headers, is missing or incorrect
That's about the most we can provide from the example you've given. But here's the other concern that will benefit you greatly in the future: "Bad Request" tells you a lot about what's happened.
More about "Bad Request" in general
If you look at ranges within HTTP status codes you'll notice a pattern in the "error" ranges.
In 4xx the requester (you) did something wrong and you can correct it.
In 5xx the responder did something wrong and you cannot correct it.
Beneath that:
In 404 Not Found it seems the request was formed well but the responder cannot find what you've asked for
In 401 Unauthorized you didn't provide any kind of identity
In 403 Forbidden you did provide an identity but you're not allowed to perform this action
But in 400 Bad Request the responder couldn't validate your request as good input at all. That means you can look at the API documentation again, compare it with your implementation, and try again.
We are having an Web API exposed by 3rd party which we do not have any control. It looks like they are wrapping the custom error message model on throwing back 400 (Bad Request).
We get custom error message model when using Postman
{
"Message": "Site Name Exists",
"ErrorId": "<some-guid>",
"ErrorCode": 400,
"GeneratedTime": "<some-datatime>",
"RequestedUri": "origin-api-uri"
}
We tried using HttpWebResponse or WebResponse to get the response from API but it throws exception with 400 code on httpWebRequest.GetResponse(). It does not give us the expected response as we get in Postman but it says 400 (Bad Request) and with default error message, 'The remote server returned an error'.
We want to get original error message as Postman. Any thoughts?
By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error, or 400 bad Request and this is very painful situation. You need to catch WebException in catch block.
refer to: Exception Handling in ASP.NET Web API
Give it a try.
catch (WebException ex)
{
StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd());
}
I have the following code in my method:
// make the FTP request
var request = (FtpWebRequest)WebRequest.Create(serverUri);
request.KeepAlive = true;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
return (FtpWebResponse)request.GetResponse();
The serverUri is valid and this works if the directory does not exist already on the server. However, if the directory does already exist a System.Net.WebException : The remote server returned an error: (550) File unavailable (e.g., file not found, no access) occurs.
Why does this exception occur when I call request.GetResponse() instead of setting the FtpWebResponse object's StatusCode to FtpStatusCode.ActionNotTakenFileUnavailable which is 550?
I find information on how to handle the exception and get the status code and description from it. But I would like to know why the exception is thrown in the first place instead of setting the response object's status code and letting the coder decide if it warrants an exception.
Because getting an error code after making an Http request matches perfectly with the Exception semantics of the language. You don't actually have a meaningful response to get back and since it is an "exceptional" case it makes sense to translate the web error to a WebException.
This is actually behaving as designed. You'll need to catch that specific exception and then interrogate the response. Per the MSDN documentation:
If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.
So, the code might look like this:
try
{
return (FtpWebResponse)request.GetResponse();
}
catch (WebException we)
{
// interrogate the WebException for the response data you're looking for
}
Information of what I have and what I am trying to achieve
I am using ServiceStack and have it up and running for what I need, however I am unable to find out how to disable the Body/Content for uncaught exceptions.
I have ServiceStack handling ALL routes.
If I navigate to a route which is not mapped to ServiceStack, I get a StatusCode of 404 (perfect) and content in the Body of the response of "Handler for Request not found: ...."
If my code throws an uncaught exception, ServiceStack will kindly return a relevant StatusCode, however it also returns a ResponseStatus with ErrorCode and Message populated.
I have DebugMode turned off, this disables the StackTrace, however I want to completely mute the entire Body of the response for exceptions.
What I have tried
I have tried a Response Filter of the following:
ResponseFilters.Add((req, res, dto)) =>
{
if (dto is Exception) res.Close();
});
it unfortunately did not work.
What I want to avoid
try{
return service.GetResponse();
} catch (Exception) {
return new HttpResult(.....);
}
My Question
How do I disable the response body for all uncaught exceptions, but still return the StatusCode? I would like null returned in the body, and StatusCodes to remain in tact.
I've tried to make my question clear, but if I have been a bit vague in any way, please ask me questions.
You should be able to override the default exception handling behavior by overriding HandleException of ServiceBase.
You can inspect the default implementation here: https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.ServiceInterface/ServiceBase.cs#L228.
I have a page (generic handler) on which I want to return the status code 500 to the client to indicate that something is wrong. I do it like this:
Response.StatusCode = 500;
Response.StatusDescription = "Internal Server Error";
And at the same time I render a friendly message telling the user that something went wrong.
But instead of seing my message, I get the default IIS message saying something like this:
Server Error
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
And if I go in to IIS and remove the error page for 500, I get this message:
The page cannot be displayed because an internal server error has occurred.
It works as intended in IIS6, but not in IIS7. What should I do to get it working in IIS7?
You need one more line in there to bypass IIS7 taking over (based on the 500 error code you set):
Response.TrySkipIisCustomErrors = true;
Reference: HttpResponse.TrySkipIisCustomErrors