laravel bad request status message in console - laravel

can someone help me how can I pass error code and message to be able to parse it in a console for example...
in my case - if I don't set any status code it will return status code 200(even tho I use rules for validation) and I can see my custom message in the console logs
but when I set 400 status code I get a generic message
public function store(StoreNewTeam $request)
{
$validator = Validator::make($request->all(),
['team.name' => 'required|unique:teams,name',
'team.level' => 'required',
'teamMembers.*.firstName' => 'required',
'teamMembers.*.lastName' => 'required',
'teamMembers.*.email' => 'required|unique:team_members,email',
]);
if ($validator->fails()){
return response()->json(['message' => $validator->errors()->first()],Response::HTTP_BAD_REQUEST);
}
but when I go to network tab I can see my custom message...
how can I get that message to console?
and additional question... if I work on API like that is it OK to stay that way since I can see my message in network tab - as well in postman?
edit:
StoreNewTeam is empty - just authorise is changed to true
since my request is array of 2 data combined I wanst able to type rules inside of StoreNewTeam

so issue was not inside of laravel, but in my axios setup
to parse error in console axios error should be set up like this
.catch(function (error) {
console.log(error.response);
});

Related

Unable to access returned error response in Axios from Laravel Lumen API

I've got a Laravel Lumen 7 RESTful API alongside a Nuxt JS front-end with Axios. My front-end makes Axios calls to the API and inside of my Lumen project I'm of course returning relevant responses and error codes. However, it appears that these responses although I can see them when I inspect the network and can see it in the preview/response tabs, I'm unable to access it from Axios in my catch() block...
If I change it to a 200 response then I can access it from my then() block but this isn't ideal.
Lumen response
return response()->json(['success' => false, 'message' => 'We\'re unable to add this domain right now, please try again shortly'], 500);
JS Axios function
/*
** Add domain
*/
addDomain () {
// add new domain
this.$axios.post(`${process.env.API_URL}/api/domains/add`, this.domainCreation).then(res => {
console.log(res)
}).catch(err => {
console.log(err) // doesn't display my Object from laravel, instead just the native error string: "Error: Request failed with status code 500"
})
}
Can anyone help?
try this err.response catch error data is inside response
this.$axios.post(`${process.env.API_URL}/api/domains/add`, this.domainCreation).then(res => {
console.log(res)
}).catch(err => {
console.log(err.response);
})
ref link https://github.com/axios/axios#handling-errors
In addition to the above answer, you should consider returning the correct response codes.
5xx error codes are for Internal Server Errors. You are probably looking to return a 422 unprocessable entity error.
More info about 500 status code: https://httpstatuses.com/500
More info about 422 status code: https://httpstatuses.com/422

TypeError: Cannot read property 'status' of undefined when receiving errors from Laravel validation

I'm trying to validate a form via AJAX using Axios with vue.
axios.post('api/registro', this.sede)
.then(response => {
this.$emit('cerrar')
})
.catch(err => {
console.log(err)
})
The error comes from the catch part, as it's coming from a Laravel validator. The response from the server is 422 and it contains a JSON with a message and the errors the server is sending.
Everything works fine if I dont try to log the error.
The problem was coming from me using interceptors in axios, I wasn't returning the errors in the interceptors properly, so nothing was coming into the catch function.
This is what I had:
axios.interceptors.response.use(null, function (error) {
// some logic
});
And this is how it should've been:
axios.interceptors.response.use(null, function (error) {
// some logic
return Promise.reject(error);
});
Thank you all so much for your help.
You can just check for errors like so:
if(err.response.data.errors){
this.errors = err.response.data.errors;
}
this.errors would be an array you can loop through using v-for to display it

Wordpress Auth + Nonces + Ajax + No Templating - Cookie nonce is invalid

I understand the process of using nonces when I create my own templates.
But I am developing a ReactJS App which uses ONLY the Wordpress REST API for pulling data, so the user never gets to the index.php, but does Ajax calls to the WP Rest Api.
Now I cannot get the nonce stuff to work.
This is what I have done so far:
I added the following endpoints:
register_rest_route('frontend', '/customer/', array(
'methods' => 'GET',
'callback' => 'get_customer'
));
register_rest_route('frontend', '/customer/', array(
'methods' => 'POST',
'callback' => 'create_user_and_login'
));
These are my functions:
function get_customer()
{
return get_current_user_id();
}
function create_user_and_login(){
// dummy data for testing
$credentials = ['user_login' => 'mail#mymail.de', 'user_password' => 'XXXX', 'remember' => true];
// create a new user/customer via woocommerce
$customerId = wc_create_new_customer($credentials['user_login'], $credentials['user_login'], $credentials['user_password']);
if(is_a($customerId,'WP_Error')) {
return $customerId;
}
// get the user & log in
$user = get_user_by( 'id', $customerId );
if( $user ) {
wp_set_current_user( $customerId);
wp_set_auth_cookie( $customerId );
}
// create new nonce and return it
$my_nonce = wp_create_nonce('wp_rest');
return $my_nonce;
}
If I now run a POST to /customer which triggers create_user_and_login(), the newly created nonce is returned in the ajax response. Then I use the returned nonce to run my next request, a GET to /customer?_wpnonce=MY-NONCE, but I get the error:
{
"code": "rest_cookie_invalid_nonce",
"message": "Cookie nonce is invalid",
"data": {
"status": 403
}
}
I checked the nonce documentation but I could not find a solution for my problem. Could it be that the sessions are out of sync? So that the nonce is created on the wrong session or wp_set_auth_cookie and wp_set_current_user are not called correctly? Or do I have to use the wp_localize_script function? This will get problematic, as I want to have the ReactJS and the Wordpress backend separated.
I got two cookies after the POST, a wordpress cookie and a wordpress_logged_in cookie.
What am I missing?
Check this answer
It seems that when you call $my_nonce = wp_create_nonce('wp_rest'); the nonce is created with the old session cookie, even when you call wp_set_auth_cookie and wp_set_current_user. But in the next request the session is updated, meaning that the nonce is wrong.
As in the answer, add the following hook (functions.php for example) to force an update of the cookie:
function my_update_cookie( $logged_in_cookie ){
$_COOKIE[LOGGED_IN_COOKIE] = $logged_in_cookie;
}
add_action( 'set_logged_in_cookie', 'my_update_cookie' );

Angular 2 HttpClient error body

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

Laravel Queue mail doesn't work, but send mail works

i have a very strange problem.
If i use laravel send mail everything works perfect.
but when i queue a mail it give a this error.
but the very strange part is, that yesterday my code did work!! without changing anything now
this works:
Mail::send('emails.empty',
$invoice, function ($m) use ($invoice) {
$m->from('hello#app.com', 'Your Application');
$m->to($invoice['customer_email'], $invoice['customer_name'])
->subject($invoice['email_subject']);
});
But this doesn't work
Mail::later(1, 'emails.empty',
$invoice, function ($m) use ($invoice) {
$m->from('hello#app.com', 'Your Application');
$m->to($invoice['customer_email'], $invoice['customer_name'])
->subject($invoice['email_subject']);
});
Also with the new 5.3 way it doesn't work
$user = new App\User();
$user = $user->find(1);
Mail::to($user)->queue(new EmailTest($user));
This is the faild job error:
Swift_TransportException: Expected response code 250 but got code "", with message "" in /private_html/dev1/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383
Stack trace:
#0 .......................
I use mailtrap to send/catch my emails. with the same settings de SEND function works! so its not the settings

Resources