In the case of a data validation error, I want to return HTTP status code 200 (OK) with my own error code.
Following is my sample error response JSON.
HttpStatusCode : 200
Response JSON
{
"isError": true,
"resultInfo": {
"resultCode": "801",
"resultMessage": "Order(s)-RNSIN000001 is already exists!!"
},
"orderStatus": null
}
Can I go with this pattern or It will be a violation of the API response pattern?
Related
I am able to send post and get request from postman but when i actually send that request from browser it is not able to fetch records and in console shows error "body: {error: "Collection 'undefined' not found"}".
tried for both Get and Post requests they both provide the data in response in POSTMAN, but in browser it does not work.shows error "body: {error: "Collection 'undefined' not found"}".
in same project at different place i am also using in-memory-data-base, to which i am able to make /GETRequest and recieve the data in response.
homepage.ts:=============
public AllItem: AllItems[] ;
getAllItems(): void {
console.log('AA');
this.itemService.getAllItems() //(this.AllItems)
.subscribe(AllItem => this.AllItem = AllItem );
console.log(this.AllItem);
console.log('EE');
}
item.Service.ts:===============
private itemsUrl = 'api/items'; // URL to web api
private allItemsUrl = 'http://*************.azurewebsites.net/items';
getAllItems(): Observable<AllItems[]>{
console.log('CC');
return this.http.get<AllItems[]>(this.allItemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<AllItems[]>('getHeroes', []))
);
}
// this get request work properly and gives response data from in-memoery-db
getItems(): Observable<Item[]> {
return this.http.get<Item[]>(this.itemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Item[]>('getHeroes', []))
);
}
in POSTMAN it gives data as
{
"items": [
{
"category": "Drink",
"item": "Coffee",
"price": "5$"
}]
}
in Browser console
core.js:15724 ERROR
body: {…}, url: "http://**********.azurewebsites.net/items", headers: HttpHeaders, status: 404, statusText: "Not Found"}
body: {error: "Collection 'undefined' not found"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 404
statusText: "Not Found"
url: "http://*************.azurewebsites.net/items"
__proto__: Object
Got the solution for this, Actually i was using in-memory-web-api at some other places in same project,
Not found collection error suggest that you have used angular-in-memory-web-api before. You need to remove everything related to that from your project, so that you are able to use external api and db.
"InMemoryWebApiModule.forRoot(InMemoryDataService)"
Angular in-memory-web-api, it replaces the HttpClient module's HttpBackend SO it needs to be removed first before using actual server and DB
After this i faced another issue that Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
For this we need to use following in our node server in Azure.
var cors = require('cors');
app.use(cors({origin: '*'}));
Executing Angular2 http call to the offline server doesn't provide much info in it's "error response" object I'm getting in the Observable's .catch(error) operator or subscription error delegate (they are both share the same info actually). But as you can see on the screen shot of the console there's actual error was displayed by zone.js somehow.
So, how can I get this specific error info (net::ERR_CONNECTION_REFUSED)?
Thanks.
Whenever server do not respond, response.status will be always equal to 0 (zero)
{
type: 3, //ResponseType.Error
status: 0, // problem connecting endpoint
}
Also note, when you are performing CORS request, but origin (url in browser) is not authorized (not in allowed list of host names configured in remote endpoint) the response would be similar to above, with exception to type attribute which will be equal to 4 = ResponseType.Opaque...
This means, connection was made, but for instance, OPTIONS request returned with headers which do not contain origin or HTTPS request was performed from HTTP origin.
You can handle the error messages so they are easier to read. This can definitely be expanded on too:
public Get() {
return this.http.get(this.URL).map(this.extractData)
.catch(this.handleError);
}
public extractData(res: Response) {
let body = res.json();
return body || {};
}
public handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
Check out this part of the docs on error handling.
Without digging in the code, my expectation is that if the server is unreachable, then no response can be returned from the server. Therefore the Response object remains its initialized state.
I cannot interecept error from http post
a part of my mservice (http post method)
addApplicationLink(applicationLink: ApplicationLink){
let body = JSON.stringify(applicationLink);
let requestHeaders = new Headers();
var headers = new Headers();
headers.set('Content-Type', ['application/json; charset=utf-8']);
let reqoptions = new RequestOptions({
headers: headers
});
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,{headers: headers});
in my component :
addApplicationLink() {
//todo
this.addNewLink = false;
/* check if must be done after call real rest service */
//this.applicationLinks.push(this.applicationLinkAdd);
this._applicationLinkService.addApplicationLink(this.applicationLinkAdd)
.subscribe(data => {
this.applicationLinks.push(this.applicationLinkAdd)
},
error => {
// handle error
console.error('this an erreor ' + error.status)
}
)
When user tries to add two same applicationlinks , the backend returns an error 409
But when I execute , error.status displays 200 in browser console
I see also in browser console
XMLHttpRequest cannot load http://localhost:7001...... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 409.
rem : Http post is made with json , thus there is a prefligth call
Have you an idea to intercept error 409 ?
In fact, your server doesn't send back the CORS header (Access-Control-Allow-Origin' header is missing). This prevent the browser from providing the actual 409 error to the Angular2 application within the browser.
You need to fix first the problem on the server and you will be able to see this 409 error.
For more details about how CORS works, you could have a look at this article:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
I am developing an app that appends all the values of the form to a FormData() object e.g. "msgBody" and sends it to the grails server-side where it is consumed by jax-rs api. I have used something like:
GrailsWebRequest request = WebUtils.retrieveGrailsWebRequest()
def params = request.getParams()
if (!(params.msgBody.length() > 0)) {
log.error("Empty message body")
}
The problem I am having is with the integration testing of that api where I have written:
def headers = ['Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryZ7dAiucrA3eTbjzI', 'Accept': 'application/json']
def content='{"msgBody":"Hello World"}'
sendRequest("/api/v1/message", 'POST', headers, content.bytes)
I keep on getting the "500 Internal Server Error" and error message:
"Caused by: java.lang.NullPointerException: Cannot invoke method length() on null object".
Why is this happening?
I have found out that you don't need to set the Content-Type in the headers and you also have to set all the fields of the FormData() object even if they are null. I did so but still I am getting the same NullPointerException message.
This Web API action returns an HTTP 500 (Internal Server Error) status code:
public IHttpActionResult Post()
{
return InternalServerError();
}
But this action returns an HTTP 400 (Bad Request) status code:
public IHttpActionResult Post()
{
return InternalServerError(new Exception());
}
I would expect both actions to return a 500 status code and the second action puts some of the error's details in the response body.
My first thought is that this is a bug but I wanted to get some other input. Is there any good reason why a 400 should be returned in the second action instead of a 500?
UPDATE:
The documentation on this method reads:
Creates an System.Web.Http.Results.ExceptionResult (500 Internal Server Error) with the specified exception.
I'm thinking more and more this is a bug.
Right, this was a known issue which was fixed after Web API 2 release...you can use the following workaround to fix this issue..example:
return new ResponseMessageResult(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, invalidOpException));
Following was the issue that was logged before:
https://aspnetwebstack.codeplex.com/workitem/1318