How to replace 400 bad request error message with a custom message - asp.net-web-api

I am creating a webapi and just wondering whether I can replace the default error message in case of 400 Bad Request.
For example, in this url (http://localhost/api/values/4) 4 is the integer type but if I pass a string intentionally (e.g. http://localhost:35453/api/values/sss), I receive an error (400 Bad Request) in the following format:
{
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult Get(Int32)' in 'WebAp__DELETE.Controllers.ValuesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
Is there any way I can replace this default error message with a custom error message of mine.

Related

problem with the payload when saving a record

when I try to add\change the value of a custom lookup and then save it, I get this error:
Exception Message: Error identified in Payload provided by the user for Entity :'', For more information on this error please follow this help link https://go.microsoft.com/fwlink/?linkid=2195293 ----> InnerException : Microsoft.OData.ODataException: An undeclared property 'ey_org_unit_hr_id' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadUndeclaredProperty(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean propertyWithValue)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithoutValue(IODataJsonLightReaderResourceState resourceState, String propertyName)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.<ReadResourceContent>b__0(PropertyParsingResult propertyParsingResult, String propertyName)
at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func`2 readPropertyAnnotationValue, Action`2 handleProperty)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState)
at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource()
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties)
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector)
at Microsoft.OData.ODataReaderCore.ReadImplementation()
at Microsoft.OData.ODataReaderCore.InterceptException[T](Func`1 action)
at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader)
at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger).
ErrorCode: -2147185383
HexErrorCode: 0x80048d19
the field's logical and schema name is "ey_org_unit_hr_id" (both of them are identical).
I opened the post request that the form sends and this is what I found:
{"ey_org_unit_hr_id#odata.bind":"/ey_businessunits(91293b20-afb7-e611-bec8-0050568c00dc)",
"ey_org_unit_hr_id#OData.Community.Display.V1.FormattedValue":null,
"ey_s_name":"test555",
"ey_b_is_doctor_house":false,
"ey_b_is_route_service_requests":false,
"ey_b_real_branch":false,
"statuscode":1,
"statecode":0}
then I opened the metadata and found out that the NavigationalProperty Name of this field is different than what is used in the post request (ey_org_unit_hr_id is used in the request but the navigational property name is ey_ey_businessunit_ey_branch_hr which is also the name of the relationship).
Photo of the navigation property name
so i tried to send a post request using postman whith the currect NavigationProperty Name and it worked without an error.
Here is the request:
{"ey_ey_businessunit_ey_branch_hr#odata.bind":"/ey_businessunits(91293b20-afb7-e611-bec8-0050568c00dc)",
"ey_ey_businessunit_ey_branch_hr#OData.Community.Display.V1.FormattedValue":null,
"ey_s_name":"test555",
"ey_b_is_doctor_house":false,
"ey_b_is_route_service_requests":false,
"ey_b_real_branch":false,
"statuscode":1,
"statecode":0}
I thought about changing the navigational property name to what is used in the original post request but I don't know if I can change the metadata.
Try this property name: _ey_org_unit_hr_id_value.
You should check your error code at the below link.
https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
AFAIK, the 0x80048d19 code will be exposed by sending request with invalid data.
In my case, I got this error code when i sent request without header "Content-Type: application/json"
I hope this can be helpful to you

How to deal with nulls in GraphQL schema

I keep getting the "Cannot return null for non-nullable field Airline.id." error when FlightSchedule.operatingAirline is null (perfectly valid as per schema) and client queries for FlightSchedule.operatingAirline.id. How to fix this? Making Airline.id, Airline.code and Airline.name as nullable fixes this but is not the right way to solve this problem because if an Airline exist, these 3 fields will always exist too. Below is my schema:
type Airline {
id: String!,
code: String!,
name: String!
}
type FlightSchedule {
airline: Airline!
operatingAirline: Airline
}
And below is my query:
getFlightSchedules {
airline
{
id
code
name
}
operatingAirline
{
id
code
name
}
}
A field will resolve to null when an error is encountered while resolving it. This includes validation errors like the one you're encountering. From the spec:
If during ExecuteSelectionSet() a field with a non‐null fieldType throws a field error then that error must propagate to this entire selection set, either resolving to null if allowed or further propagated to a parent field.
If this occurs, any sibling fields which have not yet executed or have not yet yielded a value may be cancelled to avoid unnecessary work.
In other words, if a parent field is of a particular object type, and that type has a non-nullable field, and that field resolves to null, that parent field will also resolve to null. The parent field cannot return an object that is invalid (in this case because it had a non-null field return null), so the only thing it can do is return null. Of course, if the parent field itself is non-null, this behavior is propagated up the tree until a nullable field is finally encountered.
So, why are you getting that error? Because your resolver for operatingAirline is not returning null. It is returning some kind of object (either an incomplete airline object, an array, a string or something else) that GraphQL then effectively tries to coerce into the Airline type. The id field was requested, but it resolves to null based on the object returned by operatingAirline's resolver. Since the id was requested and returned null, the entire operatingAirline field fails validation and returns null.

How to return an object or null in GraphQL?

I have the following schema:
type User {
email: String!,
user_id: String!,
img: String!,
},
type Query {
getUser(user_id: String!): User
}
The schema reflects the fact that I must return an User object. However, I can not always do this, and sometimes I need to return null. For example, if I make a request to the DB, it will return return object or null (if the user was not found).
In my GraphQL schema, I set the type for a particular field. If I try to return a different type than what I set, I get an error. How do I allow a field to return either an object or null?
According to the spec:
By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used.
In other words, types in GraphQL are nullable by default. So a field like
getUser: User
may return either a User object or null. A field like
name: String
may return either a String or null. Only by explicitly specifying a field as non-null (in SDL, by appending a ! to the type), can we specify that a field should never return null. For example:
name: String!
It's also important to note that the Promise returned in your resolver must resolve to either null or undefined in order to be coerced into a null value. In other words, if you return an empty object ({}), an empty array ([]) or some other value, GraphQL will treat this as you returning an object and not a null value!
In your schema, the email field on User is String!, meaning it cannot resolve to null. If you run a query like
query {
getUser(user_id: "1") {
email
}
}
and the resolver for getUser returns an empty object ({}), GraphQL will attempt to resolve email, return null for it and blow up because email is not supposed to be null! If, however, getUser resolves to null, none of the child fields will be resolved and you will not get any error.
According to Graphql - get full sub-object, or null if doesn't exist, you get the error you describe when you return empty object (i.e. {}) instead of null from your GraphQL function.
I had similar problem: I kept getting the "error: lack the require field" error in GraphQL response until I made sure I was actually returning null, not empty object.

Spring form tags. Allow nulls in form:select (enum)

I'm using Spring form tags for filling form with values.
I have form backing object:
public class FormInfo {
public enum Status {ON, OFF}
private Satus status;
//getter setter
...
}
And in JSP Status enum presented like this:
<form:form commandObject="formInfo " ...>
<form:select path="status">
<form:option value="null" label="Please select"/>
<form:options/>
</form:select>
</form:form>
All works fine, i.e. default message and enum values are presented in <select>.
But the status field is not required, so I want allow user to leave Status field unselected. But if form submitted without selecting status field, then I get error:
error in object 'formInfo' on field 'status': rejected value [null];
How I can set enum to null when no values is selected?
Please note I'm using JSR 303 validation. And error described above is not happens automatically, I get this error message manually from following method BindingResult#getFieldErrors().
This is my controller code:
public void myMethod(#Valid #ModelAttribute("formInfo") FormInfo sourcingDetail, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
log.error("Error during validation is occurred." + bindingResult.getFieldErrors().toString()); // <-- this is error message
}
...
}
Also please note, I didn't set any JSR-303 annotation (like #NotNull) on status field.
UPDATE:
Almost full error message which I get from calling this method BindingResult#getFieldErrors() (explained above):
Error during validation is occurred.[Field error in object 'formInfo'
on field 'status': rejected value [null];
...
[Failed to convert property value of type 'java.lang.String' to
required type 'com.my.project.model.Status' for property 'status';
nested exception is java.lang.IllegalStateException: Cannot convert
value of type [java.lang.String] to required type
[com.my.project.model.Status] for property 'status': no matching
editors or conversion strategy found],
Looks like you have the same problem as i!.
There is a method in the controller that serves as a hook where you could specify how to transform the String values, that came from the HTTP request, to a concrete object!.
The method is called initBinder, and there you attach the right behavior to do the conversion properly. I am still researching, but so far, looks good.
Take a look at this :
Form Values to be Null instead of "" in Spring
http://kaushalyas.blogspot.com.ar/2011/02/data-binding-in-spring-mvc.html
Hope it helps to found the solution!
Greetings
Victor.

MVC Ajax Int32 error

Hi when I try to do an Ajax post to my controller I keep getting this message:
The parameters dictionary contains a
null entry for parameter 'id' of
non-nullable type 'System.Int32' for
method 'System.Web.Mvc.JsonResult
GetContactsByDepartment(Int32)' in
'Intranet.Controllers.MyController'.
An optional parameter must be a
reference type, a nullable type, or be
declared as an optional parameter.
The method head looks like this: public JsonResult GetContactsByDepartment(int id)
What am I missing? I have ensured that the id is being passed through my Jquery ajax call.
Try to rename id to for example DepartmentID.
Probably an issue with your registered routes.

Resources