ASP.NET core error handling error message - c#

I am starting to work on ASP.NET core error handling, and I noticed that I am getting an error in a format
{
"errors": {},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|caeb2316-47fb93bd8a17bc0a."
}
I am trying to get a more detailed error message, but I cannot get rid of this message.
I just followed instruction on Handle errors in ASP.NET Core, but error is always there.
How can I get rid of this format of error message?

Using the below code you can create custom error response or custom problem details:
services.AddControllers()
.ConfigureApiBehaviorOptions(o =>
{
o.InvalidModelStateResponseFactory = context =>
{
var problemsDetailsFactory = context.HttpContext.RequestServices
.GetRequiredService<ProblemDetailsFactory>();
var problemDetails = problemsDetailsFactory.CreateValidationProblemDetails(
context.HttpContext,
context.ModelState);
problemDetails.Detail = "Custom Details";
problemDetails.Instance = context.HttpContext.Request.Path;
problemDetails.Type = "https://tools.etf............";
//problemDetails.Status = StatusCodes.Status422UnprocessableEntity;
problemDetails.Status = StatusCodes.Status400BadRequest;
problemDetails.Title = "One or more errors on input occured";
return new BadRequestObjectResult(problemDetails)
{
//ContentTypes= {"application/custom+json"}
};
};
});

Related

How to disable default error response for Api Versioning

Good evening, everybody. Trying to implement Api Versioning for my project. Faced with the problem that receiving default errors template response for request. Look code 1
{
"error": {
"code": "UnsupportedApiVersion",
"message": "The HTTP resource that matches the request URI 'https://localhost:5003/v2.3' does not support the API version '2.3'.",
"innerError": null
}
}
But I have my own error response template that want to receive.
{
"traceId": "0HMF1NONVN8SF:00000002",
"errors": [
{
"message": "",
"source": ""
}
]
}
As I understand I could implement my own ErrorResponseProvider, but could I avoid doing that?
How could I can disable ErrorResponse for ApiVersionOptions?
My api version configuration:
services
.AddApiVersioning(opt =>
{
opt.ApiVersionReader = new UrlSegmentApiVersionReader();
opt.UseApiBehavior = false;
opt.DefaultApiVersion = ApiVersion.Default;
opt.AssumeDefaultVersionWhenUnspecified = true;
})
.AddVersionedApiExplorer(opt =>
{
opt.GroupNameFormat = "'v'VV";
opt.SubstituteApiVersionInUrl = true;
});
Versions:
.NET 6
ASP.NET Core 6
Microsoft.AspNetCore.Mvc.Versioning 5
Actually I didn't find the way to disable it. However, I found the solution for my case. First of all, I implemented my CustomErrorResponseProvider for ErrorResponses.
public class CustomErrorResponseProvider : DefaultErrorResponseProvider
{
public override IActionResult CreateResponse(ErrorResponseContext context)
{
switch (context.ErrorCode)
{
case "UnsupportedApiVersion":
throw new UnsupportedApiVersionException("Url", context.Message);
}
return base.CreateResponse(context);
}
}
Than started throw necessary exception from it. And that's all!
As my middleware looks like this(img below), my ErrorHandlingMiddleware didn't catch an exception, because it was generated by default api versioning error handler.

UnknownError sending messages to Teams

I'm trying to send a message into a channel inside an organization's Teams.
I have deployed the app successfully, and I get an Authentication token.
When I do as stated here to send messages to a chat, via C# as follows:
_token = await _authenticationHelper.GetAuthenticationToken();
AccessToken = _token;
string teamId = "xxx-xxx-xxx-XX-Xxxxx";
string channelId = "...thread.skype";
var val = await HttpPost($"/teams/{teamId}/channels/{channelId}/messages",
"{ \"body\": { \"contentType\": \"html\", \"content\": \"Hello World\" } }", endpoint: "https://graph.microsoft.com/beta");
get an error from Microsoft Graph Stating:
System.Exception: {
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"request-id": "44b6397d-aae4-4f60-a2fd-200070c64908",
"date": "2019-04-18T12:30:02"
}
}
}
This error is not descriptive so I don't really know what went wrong.

Exception in server by android retrofit

I'm trying to throw an exception on my server so that my application on Android gets this exception and shows it, I inquired about this service at the postman, the answer I can get, was the message I send from the server "the code is not found in bd. " but in the application only the error "An error has occurred" is displayed.
this is the service and the throw:
internal TDDC InfoTD()
{
throw new Exception("the code is not found in bd");
}
this is the postman
{
"Message": "An error has occurred.",
"ExceptionMessage": "the code is not found in bd",
"ExceptionType": "System.Exception",
And in android
String errorResponse = response.errorBody().string();
JSONObject object = new JSONObject(errorResponse);
if (object.has("Message"))
message = String.valueOf(object.get("Message"));
¿ how i can get the message in "ExceptionMEssage" in android application ?, in this I use Retrofit 2
Its a bad practice to implemt or parse network error responses on your each service call.
Instead you can centralize a catch or network error like this.
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
okhttp3.Response response = chain.proceed(request);
// check your network responses here
if (response.code() == 500) {
startActivity(
new Intent(
ErrorHandlingActivity.this,
ServerIsBrokenActivity.class
)
);
return response;
}
return response;
}
})
.build();

php soap fatal Error but i want the error from the webservices

I have a soap connection established, I need to give the webservice a key to get the methodes working. But if i give a wrong key it gives me a Fatal Error:
Fatal error: Uncaught SoapFault exception: [s:Client] Wrong apiKey in
But I need the go "past" this fatal error and get the error from the webservice it self. Because it has a build in Error class for if the key is wrong.
This is the code I use:
try{
$client = new SoapClient("http://portal.webservice.com/AccountService.svc?singleWsdl");
}
Catch(exception $e){
$response = $client->CheckUserCridentialsValid(array(
"apiKey" => "$key",
"userName" => "$username",
"password" => "$password"));
if($response->CheckUserCridentialsValidResult) {
$response_model = $client->Account(array(
"apiKey" => "$key",
"userName" => "$username"));
$_SESSION['AccountID'] = $response_model->AccountResult->AccountID;
$_SESSION['UserName'] = $username;
redirect_to('index.php');
} else {
$_SESSION['username'] = $username;
$_SESSION['message'] = $message = "Username or Password incorrect! <br>";
redirect_to('welcome.php');
}}
The script will not get past the line where "apiKey" => "$key",.
So I never reach the point were I can get a error from the webservice. I build in a try and catch, but then the I just get a blank page and no redirect with a message.

Google+ Moments:Insert AddActivity generic error

I'm trying to publish an app moment for Google+. The app successfully completes the authentication process and receives the access token. The problem happens when I try to call the Moment.Insert API on "https://www.googleapis.com/plus/v1/people/me/moments/vault", always returns this unspecified error message
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
The API steps I'm following are the ones listed here https://developers.google.com/+/api/latest/moments/insert and the request looks like this
{
"target": {
"kind": "plus#itemScope",
"name": "Sample Test for Google Plus REST API",
"id": "88370F18-81A4-47F5-BC2F-19EDBE326A20",
"url": "http://schema.org/Thing"
},
"type": "http://schemas.google.com/AddActivity",
"kind": "plus#moment"
}
I also add the access token to the request header & the api key to the url as a parameter.
I don't know if I'm missing something here but it may worth saying that I receive the exact same error message when using the API explorer in Google Dev. Console.
Thanks in advance for any insights
This is the moment declaration that worked for me. For some reason, the description field is required and not adding it would produce this strange error message.
var client = new RestClient();
var moment = new
{
kind = "plus#moment",
type = "https://schemas.google.com/AddActivity",
target = new
{
kind = "plus#itemScope",
id = "GENERATE-A-POST-ID-HERE",
type = "https://schemas.google.com/AddActivity",
name = "SOMTHING-TO-POST",
description = "SOMTHING-TO-POST"
}
};
var request = new RestRequest(string.Format("{0}?key={1}", GOOGLE_POST_URL, GOOGLE_APP_ID), Method.POST);
request.AddHeader("authorization", "BEARER-ACCESS-TOKEN-RECEIVED-BEFORE");
request.AddBody(moment);
client.ExecuteAsync(request, OnPostCompleted);
I'm using RestSharp library to handle the REST operations.
Hope this would help.

Categories