Externalize domainString Xamarin (android) - exception

I'm writing an app in Xamarin and was wondering if it's possible to externalize my strings I use in exceptions.
For example if I write in my code
throw new Exception("This is an error");
How can I externalize the errormessag "this is an error" ?
I already tried something like this :
throw new Exception("#string/errormessage")
and added errormessage to the Strings.xml file, but that didn't work.
Does anybody know if this can be done?

Assuming this is in your values\Strings.xml:
<string name="stackoverflow">StackOverflow Custom Exception String</string>
You can use it as your custom exception message via:
button.Click += delegate {
throw new Exception(this.Resources.GetString(Resource.String.stackoverflow));
};

Related

Error handling in Blazor server Razor Component

How to handle unahandled exceptions in blazor server razor component, In page model, I'm handling with try catch block, but some errors come from razor file and the circuit breaks, application stops. Kindly suggest me the solution to handle this.
I read alot about this issue and what I found that there is no way to make a global error handling right now for blazor, you can handle the error that related with http request like this:
if (!response.IsSuccessStatusCode)
{
var statusCode = response.StatusCode;
switch (statusCode)
{
case HttpStatusCode.NotFound: _navigation.NavigateTo("/Notfound", true);
break;
case HttpStatusCode.Unauthorized: _navigation.NavigateTo("/Error");
break;
default: _navigation.NavigateTo("/Error");
break;
}
throw new ApplicationException($"Reason: {response.ReasonPhrase}");
}
You need also to be carefull about using try catch inside blazor component with some proberty [inject] becuase maybe your blazor circuit will fail!.
You can read more about that in microsoft documents and correct if I am wrong.

Exception details in ABP framework

I wanna return the details of exception with ABP .NET Core, what I noticed is when I go to AbpAuditLogs table and App_Data\Logs logFile they contain the exception in details but when I use below method to return the exception it shows only general exception without any details (500 Internal Server Error)
try{
:
:
:
}
catch (Exception ex)
{
throw new System.ArgumentException(ex.InnerException.Message.ToString(), "original");
}
So, How could I return the specific Exception for the user for Example Email Validation Exception and so on?
Update:
I will explain more to make the question more clear :
The way that I handled the exception is attached with this question above .
The problem is when hitting a request on the service from swagger or Postman always see General Error with status Code 500 without any details and that force me to review the details of the exception from Log File or Log Table , I wanna see the details of the exception (e.g FileNotFoundException ) directly from Swagger or Postman without return back to Log File or AbpAuditLogs Table.
I think User Friendly Exception will work for you.
Because if an exception implements the IUserFriendlyException interface, then ABP does not change it's Message and Details properties and directly send it to the client.
throw new UserFriendlyException(
"Username should be unique!"
);
You can find more information here.
Actually, I found the answer in this question for #Mehdi Daustany .what I did is exactly what #Mehdi Daustany answered, I've added below code :
if (_env.EnvironmentName.ToLower() == "development")
Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;
under ***.Web.Core then the details of exception appeared in the Swagger
services.Configure<AbpExceptionHandlingOptions> (options =>
{
options.SendExceptionsDetailsToClients = true;
});
Above code will configure abp to return all the exception details. Just add it to the configuration.

XML to JSON in Camel Routing not working

I am trying to convert the XML message to JSON using camel router and save it into a file. Getting the XML message from the source and saving it to destination file etc are working. But when I try to convert to JSON, it did not work. I did not even throw any error/exception in logs. I am running on OSGI container
public class CamelRouter extends RouteBuilder {
#Override
public void configure() throws Exception {
from("file://C:/test/Sample.xml")
.routeId("file-to-file")
.log(LoggingLevel.INFO,"RouteID file-to-file !!!!! starting")
//From XML to JSON
.bean(CamelRouter.class, "convertXmlToJson")
.log(LoggingLevel.INFO,"From XML to JSON !!!!! Done")
.to("file://C:/test/JSONMessages")
.log(LoggingLevel.INFO,"Converted Message Saved successfully");
The bean method to convert XML to JSON convertXmlToJson is shown below
public String convertXmlToJson(String msg) {
log.info("NOW calling JSON conversion");
String jsonStr = null;
log.info("MESSAGE conversion starting : "); //After this message nothing happened
XMLSerializer xmlReader = new XMLSerializer();
log.info("MESSAGE before conversion : " + msg);
jsonStr = xmlReader.read(msg).toString();
log.info("JSON data : " + jsonObj.toString());
return jsonObj.toString();
}
Is anyone know why it is not executing the XMLSerializer portion. I tried this approach because the camel-xmljson's marshal().xmljson() call also give me the same results. Nothing happened after the xmljson() call in my camel routing.
Things that I checked are:
camel-xmljson feature up and running in OSGI
Dependencies mentioned in the Apache XmlJSON website added in my pom file, xom, camel-xmljson etc.
Am I missing anything here? Please help
The problem with your code route is that your bean component handler method resides within your route builder class, plus you invoke the bean component in a way that triggers another instantiation of that route builder class.
Personally, I would move convertXmlToJson to an appropriate utility class. That way you reduce mix of concern in the route builder and the bean component should work fine.
Alternatively, your route might work, if you invoke the bean component like this:
.bean(this, "convertXmlToJson")

symfony 1.4: How to pass exception message to error.html.php?

I tried using special variable $message described here http://www.symfony-project.org/cookbook/1_2/en/error_templates but it seems this variable isn't defined in symfony 1.4, at least it doesn't contain message passed to exception this way throw new sfException('some message')
Do you know other way to pass this message to error.html.php ?
You'll need to do some custom error handling. We implemented a forward to a custom symfony action ourselves. Be cautious though, this action itself could be triggering an exception too, you need to take that into account.
The following might be a good start. First add a listener for the event, a good place would be ProjectConfiguration.class.php:
$this->dispatcher->connect('application.throw_exception', array('MyClass', 'handleException'));
Using the event handler might suffice for what you want to do with the exception, for example if you just want to mail a stack trace to the admin. We wanted to forward to a custom action to display and process a feedback form. Our event handler looked something like this:
class MyClass {
public static function handleException(sfEvent $event) {
$moduleName = sfConfig::get('sf_error_500_module', 'error');
$actionName = sfConfig::get('sf_error_500_action', 'error500');
sfContext::getInstance()->getRequest()->addRequestParameters(array('exception' => $event->getSubject()));
$event->setReturnValue(true);
sfContext::getInstance()->getController()->forward($moduleName, $actionName);
}
}
You can now configure the module and action to forward to on an exception in settings.yml
all:
.actions:
error_500_module: error
error_500_action: error500
In the action itself you can now do whatever you want with the exception, eg. display the feedback form to contact the administrator. You can get the exception itself by using $request->getParameter('exception')
I think I found a much simpler answer. On Symfony 1.4 $message is indeed not defined, but $exception is (it contains the exception object).
So just echo $exception->message.
Et voilĂ !
I've found another trick to do that - sfContext can be used to pass exception message to error.html.php but custom function have to be used to throw exception. For example:
class myToolkit {
public static function throwException($message)
{
sfContext::getInstance()->set('error_msg', $message);
throw new sfException($message);
}
than insted of using throw new sfException('some message') you should use myToolkit::throwException('some message')
To display message in error.html.php use <?php echo sfContext::getInstance()->get('error_msg') ?>

Zend AMF and exception handling

I have created an Zend AMF service using the FlashBuilder tools. What I wanted to try was to change one of those automatically created methods to throw an exception in order to see the behaviour. Instead of the exception being serialized back to my Flex app it gives me the following:
[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:345]
at mx.rpc::Responder/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\Responder.as:68]
at mx.rpc::AsyncRequest/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:113]
at NetConnectionMessageResponder/channelDisconnectHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:684]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.messaging::Channel/disconnectSuccess()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\Channel.as:1214]
at mx.messaging.channels::NetConnectionChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:175]
at mx.messaging.channels::AMFChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:355]
at mx.messaging.channels::AMFChannel/statusHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:445]
The channel disconnects...
[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]
This is the code:
public function getAllUser() {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);
while (mysqli_stmt_fetch($stmt)) {
$row->created_on = new DateTime($row->created_on);
$row->modified_on = new DateTime($row->modified_on);
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
$errorCode = 1;
throw(new Exception('the error message you want', $errorCode));
return $rows;
}
Notice the throw statement:
throw(new Exception('the error message you want', $errorCode));
I really didn't expect this. How can I make it work?
Thank you in advanced!!!
Zend Amf is just a serialization protocol of response types to cast them into the AMF format. No error messages are sent back as they normally have sensitive security information in them. Most other PHP amf serialization do not work this way. If you have an exception you need to catch it and convert it to a standard support response type. Also in any of your code every Try needs a Catch as it is not a control structure even if PHP allows you to get away with it.
If you have configured your endpoint to not be production and just need it for debugging.
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('the error message you want', $errorCode);
Well it does serialize the exception message and code which does the job for us. Partially but does it. I didn't notice that the service component I copied the code from in my question contained an exception handler which would suppress the exception and just disconnect the channel. I removed the exception handler letting the exception bubble up to Zend which in turn send the exception message and message code to the client.
I would like to have the actual exception sent as an AS3 object but what can I say. In this way I would have the properties of the exception serialized also. Unfortunately the same goes for custom exceptions.