I have a little problem with DingoAPI and Vue.js when I'm trying to get my error message from response. I think the browser is replacing my custom message by the default one. Here is my code:
PHP script
if($request->readerId){
Return succes (this works properly)
else{
return $this->response->error(
'No reader',
400 //(or diffrent code)
);
}
Vue.js script
await axios.post(API_URL + 'card/', {
some data
}, {
headers: {
headers
},
}).then(({data}) => {
context.commit(SET_RESPONSE, data);
}).catch((error) => {
console.log(error.message);
throw error
})
When I'm trying to look on my message in the network tab I can see (so DingoAPI did it correctly):
{"message":"No reader","status_code":400}
But when I'm using console.log(error.message) or trying to show it on the page there is standard error message:
Request failed with status code 400
Is there a way to set error message with DingoAPI and catch it in my .js script?
Maybe I need to write my own custom exception?
What you want is access to the data of the response from your error variable.
console.log(error.response.data.message); // No reader
Otherwise you can log error.response to see the object:
console.log(error.response);
If you wonder why it's printing Request failed with status code 400:
The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.
Source: https://github.com/axios/axios/issues/960#issuecomment-309287911
Related
I'm currently building a single page application based on Laravel and VueJS.
Is there any better way then mine to handle errors with axios?
This is how I currently do it when a user clicks on login button:
VueTemplae:
methods : {
authenticateUser() {
axios.post('/api/login', this.form).then(() => {
this.$router.push({name : 'home'});
}).catch((error) => {
this.error = error.response.data.message;
});
}
}
Api route:
public function login() {
try {
// do validation
} catch(Exception) {
// validation failed
throw new Exception('login.failed');
}
// manually authentication
if(Auth::attempt(request()->only('email', 'password'))) {
return response()->json(Auth::user(), 200);
}
// something else went wrong
throw new Exception('login.failed');
}
Unfortunately, throwing an exception always prints an internal server error into the console.
If I return something else than an exception, axios always executes then().
Is there any way to prevent this or a better way to handle axios responses?
Thank you!
Your API needs to return a response with a 4XX status code in order for the catch block to fire in your Vue component.
Example:
After you catch the error on the API side, send a response with status code 400 Bad Request. It will be formatted similarly to your successful login response, but with an error message and 400 status code instead of 200.
I ask the help of knowledgeable people
im create a RESTfull API project on Vue.js (Vuex also)
And im get small problem
The server to which I am sending the request is down why how idn
Can someone tell me how can im detect this message from response
This response dont have any massege, error, status, statusText, text, preview and response
All this field is empty
If someone have expirience about this or some info I will be very grateful for that
You can do something like this to handle these cases:
submitRequest() {
axios.post('/api/test', this.testData)
.then(response => {
// handle success
})
.catch(function(error) {
// handle error
if (error.response) {
// The request was made and the server responded with a status code
} else if (error.request) {
// YOU CAN HANDLE IT HERE
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
}
});
}
I have been trying to diagnose a http problem for what seems forever now.
I thought I would go back to a very simple sample Ionic (Angular) application I can use to test, where I have the following test code...
public onClick() : void {
this.http.get(this.url).subscribe(res => {
this.result = res.statusText;
console.log(res);
}, error => {
this.result = `failed ${error.statusText}`;
console.log(error);
});
}
The url just comes from an input.
If I force an error, (eg put an incorrect url), I notice the error from the observable always has a status os 0, and no statusText. In the browser network tab, I see the 404 as expected...
identityx 404 xhr polyfills.js:3 160 B 10 ms
Is there a way to get better error information back from the http call, rather than just 0 all the time (and no status text)? I've look through the error object, but can't see anything.
Thanks in advance!
I'm using the new (4.3) HttpClient in angular to POST data to my backend server:
this.httpClient.post<View>(`/path`, data).subscribe(
(view: View) => console.log("Success"),
(error: HttpErrorResponse) => {
console.log(error)
this.errorMessage = <any>error.error;
});
);
This call generates an (expected) error (409), but for some reason, the logged error does not contain the body of the error sent from the server. I can see the status code, but the error.error field, which should contain the response body is missing. Anyone have any ideas what could be wrong?
I've tested the backend call using curl, and can see the response body from the server.
Is your error body coming back as JSON or un-formatted text/other? I had a similar problem until i realized the body returned with the error result was a simple string. I had to change the call to something similar to this (forgive the lack of type-safety here):
this.http.post('http://address', body, { responseType: 'text' })
.subscribe(data => {
this.result = data['value'];
this.router.navigate(['/route']);
}, (error: HttpErrorResponse) => {
this.error = error.error;
this.router.navigate(['/error']);
});
This is a known bug in angular which is throwing an exception during the json parsing and not populating the error field:
https://github.com/angular/angular/pull/18466
I successfully implemented client editors and a server side API.
Now I'm adding more validation at the server side, and besides returning the proper HTTP code (200 for OK, 4xx for other uses, 500 for errors, etc.) I want to return a list of validations that failed after the submission generated by Model.save().
I run it this way:
myModel.save({
success: function (a, operation, c) {...},
failure: function (a, operation, c) {...}
});
But if there was a failure, the operation object only have the response status and its statusText, all through
operation.error.status // i.e. 409
operation.error.statusText // "Conflict"
But server side a detail of the failing validations (mostly domain level ones) are being added to the response.
Is there a way I can get what the server sent as the body of the HTTP response to the PUT/POST submission?
Do I have to return it using a particular JSON structure?
EDIT:
I'm now returning this as the body of the HTTP Response (with code 4xx):
{
data: {/* the record serialized */},
success: false, // or true if everything went ok
message: "This failed because X and Y."
}
Thanks in advance.
For some reason Ext is not attaching the response content to the error object, but it triggers an exception event if there is a failure.
So what we did was to handle the "exception" event of the model's proxy, and then we will have access to the XHR response, being able to do whatever we want with it.
myModel.getProxy().on('exception', this.onProxyException, this);
The handler is as follows:
onProxyException : function (proxy, response, operation) {
var errors;
errors = Ext.JSON.decode(response.responseText).message;
/* Whatever is needed with the errors */
}
In this example we asume the errors come in JSON format, they could be a simple text string, which wouldn't require the use of decode().
According to this blog:
http://code.tonytuan.org/2013/07/extjs-get-server-response-in-modelsave.html
You can write code like this:
model.save({
success: function (record, operation) {
// json response from server
console.log(operation.response);
},
failure: function (record, operation) {
// undefined
console.log(operation.response);
// json response from server
console.log(operation.request.scope.reader.jsonData);
}
});
in reader block add: messageProperty: 'message'
from server return: success:false, message: 'error test'
from failure get error:
failure: function (records, operation) {
Ext.Msg.alert('error', operation.error);
}