Yii2 How to handle Swift_TransportException exception? - exception

When trying to send mail using swiftmailer I am getting the following error:
Expected response code 250 but got code "550", with message "550 User test#test.com has exceeded its 24-hour sending limit. Messages to 250 recipients out of 250 allowed have been sent. Relay quota will reset in 1.47 hours.
I have put the swiftmailer in the try catch block as follows:
public function sendMail($emailTemplateName, $subject, $body, $fromEmail, $toEmail)
{
try
{
return Yii::$app->mailer->compose(['html' => $emailTemplateName], ['emailBody' => $body])
->setFrom([ $fromEmail => Yii::$app->params['siteTitle'] ])
->setTo($toEmail)
->setSubject($subject)
->send();
}
catch(Swift_SwiftException $exception)
{
return 'Can sent mail due to the following exception'.print_r($exception);
}
}
I also tried with Swift_SwiftException and Exception but exeption doesn't get caught.
How can I handle this exception?

Ok got it. I needed to use \Swift_TransportException in catch.

Related

Caught exception: TypeError: listener is not a function while publish redis client using node v16.16.0, redis-cli 7.0.0 & "redis": "^4.2.0",

When using node v16.16.0, redis-cli 7.0.0 & "redis": "^4.2.0"
getting such exeption below:
Caught exception: TypeError: listener is not a function Exception
origin: uncaughtException[2022-07-18T07:39:30.386Z] process.on
uncaughtException ERRORCODE 105199 TypeError: listener is not a
function
at Function._RedisCommandsQueue_emitPubSubMessage (/mnt/c/Projects/konnectcore/app/sse/sse/node_modules/#redis/client/dist/lib/client/commands-queue.js:241:9)
at RedisCommandsQueue._RedisCommandsQueue_handlePubSubReply (/mnt/c/Projects/konnectcore/app/sse/sse/node_modules/#redis/client/dist/lib/client/commands-queue.js:283:100)
It's working fine while using node redis "redis": "^2.8.0".
I had a similar issue where I was using probably some old way of subscribing and receiving the messages. Something like this:
sub.on('message', (channel, message) => {
redisClient.hSet('values', message, someFunction);
});
sub.subscribe('channel');
I hope you are using the right way of publishing and subscribing to a channel in redis client. Here is one example from their documentation:
// This is how you create the client
import { createClient } from 'redis';
const client = createClient();
// This is the subscriber part
const subscriber = client.duplicate();
await subscriber.connect();
await subscriber.subscribe('channel', (message) => {
console.log(message); // 'message'
});
// This is an example of how to publish a message to the same channel
await publisher.publish('channel', 'message');
Here is the link if you would like to see some more details about publishing and subscribing of the messages using node-redis client: https://github.com/redis/node-redis#pubsub

Catch return json from POST with Axios when error 400 (Bad Request) occurs

I am making an http request in an api using React Native with Axios, I can get json and parsear it when the callback is 200, however, for example, when I call a method, for example, to register the user and step an email from a user who is already registered, he returns me an error 400 (Bad Request) but he also brings a json with the error message ("user already registered"). I need to get this error message since it is variable in the API and show to the user, but when I try to give it a console.log I get the following error:
json's return is this:
and my call code looks like this:
How to get this json even with return 400 in catch?
Thank you.
inside of your catch Block, the error object also provides you with a response body
//... your request here
.catch(error => {
console.log('response: ', error.response.data);
});
console.log(error) is calling the toString method of the error object which doesn't show you the response body.
error.response.data should give you the right content. Take a look at this part of the axios docs

Express res.status(200).json(...) only sending json message. How to retrieve status code?

After a successful creation of new item in my database I send:
res.status(201).json({message:"Successfully Registered"});
On my angular front end I am able to console.log(res) and receive:
{message: "Successfully Registered"}
1) How do I get the status code on the front end? res.status returns undefined. The only response I'm getting is the JSON.
2) What would be the best way to confirm successful desired api calls? For example, when I log in and credentials are correct, should I check for a 200 and then proceed? Or send a custom JSON message and check if the message for example says "Successful login" then proceed?
A little bit late, but another option is to include the status in the JSON object:
res.status(201).json({message: "Successfully Registered", status: 201})
Now you can check the status in the front end doing res.status and use this to proceed with another action.
1- You can do res.status(200).send("You message here");
2- I would say your best option when doing the login and authenticating credentials is to create a session as such
req.session.user = req.body.username //username is the name attribute of the textfield
and then redirect to any page you'd like/you can also set status to 200
res.status(200);
I'm not familiar with Angular, but looking at the docs:
See https://angular.io/api/http/Response
You'll need to do something like:
http
.request('example.com')
.subscribe(response => console.log(response.status));
Sure, checking for 200 is fine. Typically with a REST API (inferred from what you've shown), after a login you're given back a JWT along with 200 OK. And any subsequent API all with that JWT will also yield a 200 OK along with the response body which is usually JSON.
You should tell your angular http client that you want to get the response status. By default, angular deserialize the response body, but you can set request option.observe:'response' to do so.
postData(model: MyModel): Observable<HttpResponse<{status: string}>> {
return this.http.post<{status: string}>(
model, { observe: 'response' });
}
See https://angular.io/guide/http#reading-the-full-response for details.
PS: sending a { status: 'message' } is not very useful, you may return an { id } or even nothing.
res.status(200).json({
status: 'success',
results: tours.length,
data:{
tour:tours
}
});
Usually, Jsend is a good choice to response, and also by convention. Absolutely you can see the 'status' in response data and the actually data you want in the data.
according to the angular guide, we can add observe in the options of our request.
getforgetpassword(email: string): Observable<any> {
const url = this.gatewayUrl + `newPasswordFor/${email}`;
return this.http.get(url, {observe: "response"});
}
using observe type as response will give total response along with request status, which you can use in your logic of controller.

Xamarin Social component fails to retrieve Twitter json stream

I'm using the following to read Twitter json. It works with one uri and not another. The uri's work with the Twitter API console but not Xamarin.Social. I have read and write permissions on the Twitter app so I can't see where I'm going wrong.
https://api.twitter.com/1.1/account/settings.json <-- works
https://api.twitter.com/1.1/users/show.json?screen_name=AUserName <-- fails (see error below)
request.GetResponseAsync ().ContinueWith (response => {
if (response.IsFaulted)
{
Console.WriteLine (response.Exception.Flatten ());
}
var json = response.Result.GetResponseText ();
System.AggregateException: One or more errors occured ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x0030c] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1606
at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00141] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1423
--- End of inner exception stack trace ---
--> (Inner exception 0) System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x0030c] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1606
at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00141] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1423
[quick google search gave this but not sure if its relevant: https://dev.twitter.com/discussions/15206]
// UPDATE ***********
Does this extra infor help or you need more details? If so then what details are required?
public Account Account
{
get
{
var task = Service.GetAccountsAsync ()
.ContinueWith (accounts =>
{
return accounts.Result.ToList ().FirstOrDefault ();
});
return task.Result;
}
set
{
AccountStore.Create ().Save (value, SocialPlatform.ToString ());
}
}
// later on
// when endpoint = "https://api.twitter.com/1.1/account/settings.json" <-- works, json returned
// when endpoint = "https://api.twitter.com/1.1/users/show.json?screen_name=XXXX" <-- IsFaulted with above error,
var request = Service.CreateRequest ("GET", endpoint, Account);
request.GetResponseAsync ().ContinueWith (response => {
if (response.IsFaulted)
{
Console.WriteLine (response.Exception.Flatten ());
return;
}
var json = response.Result.GetResponseText ();
Console.WriteLine (json);
});
It seems like you are not authorised when you make this call.
From Xamarin.Social documentation.
Xamarin.Social uses the Xamarin.Auth library to fetch and store
Account objects.
Each service exposes a GetAuthenticateUI method that returns a
Xamarin.Auth.Authenticator object that you can use to authenticate the
user. Doing so will automatically store the authenticated account so
that it can be used later.
The reason why it works in Twitter API console is that you have authorised there prior to making a call.
If you are already authorising in your app then please post the code you use to authorise.

Kohana_Request_Exception [ 0 ]: Unable to find a route to match the URI:

i have a kohana site and i want to put it into production, but i have a problem i don't know how to solve best:
if someone accesses a uri that doesn't exist, relatively to my website, an error page appears, with the header message:
Kohana_Request_Exception [ 0 ]: Unable
to find a route to match the URI: (and the uri here)
i wonder if I can do something to redirect the user to a standard 404 page, when he/she accesses such a URI,can I?
thank you very much!
You can wrap your $request->execute() in your APPPATH/bootstrap.php with a try/catch block and then do whatever you want.
Mine looks like this...
try
{
// Attempt to execute the response
$request->execute();
}
catch (Kohana_Request_Exception $e)
{
if (Kohana::$environment === Kohana::DEVELOPMENT) throw $e;
// Log the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Create a 404 response
$request->status = 404;
$request->response = Request::factory('errors/404')->execute();
}
catch (Exception $e)
{
if (Kohana::$environment === Kohana::DEVELOPMENT) throw $e;
// Log the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Create a 500 response
$request->status = 500;
$request->response = Request::factory('errors/500')->execute();
}
Ideally PHP would support finally { ... } and I could do the logging and possible re-throwing there, but what can you do?
You can handle all errors the same way it is described in the userguide for http exceptions:
http://kohanaframework.org/3.1/guide/kohana/errors#http-exception-handling
Try out this one
define('IN_PRODUCTION', TRUE);
// Instantiate your Request object
$request = Request::instance();
try
{
$request->execute();
}
catch (Exception $e) // if its not valid, it gets caught here
{
if (! IN_PRODUCTION) // if this is Development, its displays the error
{
throw $e;
}
// if its IN_PRODUCTION, it does the following:
// Logs the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Marks the status as 404
$request->status = 404;
$request->response = $request->factory('sitemap')->execute();
}
// then continues on with the request process to display your custom 404 page
$request->send_headers()->response;
echo $request->response;