I have an exception I need to write a catch statement for that will catch only this exception.
The exception is:
var exception = new Exception("", new Exception("", new Exception("Violation of UNIQUE KEY constraint 'UKC_Invoice_Organisation'")));
Anyone know how to write the catch?
Besides the initial 'oh god why' response...
catch (Exception e)
{
if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause().getMessage().equals("Violation of UNIQUE KEY constraint 'UKC_Invoice_Organisation'")
{
//do special handling here
} else
throw e;
}
That said, reconsider why you have that type of exception format. Consider extending Exception so you can write a catch (MyCustomException e) block instead.
Related
In my application, Need to handle exceptions in two ways:
Can be handled by Front desk
Try
{
//code
}
catch(Exception ex)
{
Exception("Contact Admin");
}
Displaying user friendly exact error message to user that can be handled by users itself.
Try
{
enter code here
}
Catch(Exception ex)
{
`code here`
}
How to achieve the 2nd way in application?
The way I have seen it previously are the following:
To provide an optional list of user messages as part of your response:
Example:
MyExtendedObject o = new MyExtendedObject();
try {
// do your processing
o.setValue(...);
return o;
} catch (Exception e) {
log.error(e);
o.addErrorMessage("The processing has been unable to complete, please try again");
// getValue() will be empty for the front-end.
return o;
}
If you are in a web application, Return a user-friendly message as part of your http error response
I am working with callBack flow to observe a Firestore document. My flow needs to throw ResourceNotFoundException when the document being watched gets moved or deleted by some other person using the app. Below is my code for the flow
fun observeDocument(collectionId: String, documentId: String) = callbackFlow {
database.collection(collectionId).document(documentId)
.addSnapshotListener { documentSnapshot, firebaseFireStoreException ->
if (firebaseFireStoreException != null)
throw firebaseFireStoreException
if (documentSnapshot == null || !documentSnapshot.exists()) {
throw ResourceNotFoundException("")
}
try {
offer(documentSnapshot.toObject(PrintOrder::class.java))
} catch (e: Exception) {
}
}
awaitClose { }
}
and I am collecting the above flow in the ViewModel by using the following code
viewModelScope.launch {
repository.observeDocument(collectionId, documentId)
.catch {e->
_loadedPrintOrder.value = LoadingStatus.Error(e)
}
.onStart {
_loadedPrintOrder.value = LoadingStatus.Loading(application.getString(R.string.one_moment_please))
}
.collect {
_loadedPrintOrder.value = LoadingStatus.Success(it!!)
}
}
Now, the problem is catch operator is not catching the exception thrown from the flow (ResourceNotFoundException). I have even tried wrapping the flow collection code inside a try-catch block. Even the try-catch block fails to catch the exception and the app crashes.
How can I catch the Exception which is thrown from the callBackFlow during collection of the flow?
The catch operator catches exceptions in the flow completion. It will catch only if the flow completes normally or exceptionally. As you saw, it will never be thrown inside a flow builder. Moreover, your flow never completes since you are using awaitClose to keep him alive.
Since this builder uses a Channel under the hood, you can close it manually with non-null cause in order to complete the flow exceptionally:
abstract fun close(cause: Throwable? = null): Boolean
So you can use a try/catch inside the callbackFlow builder to close it manually as follows:
database.collection(collectionId)
.document(documentId)
.addSnapshotListener { documentSnapshot, firebaseFireStoreException ->
try {
if (firebaseFireStoreException != null)
throw firebaseFireStoreException
if (documentSnapshot == null || !documentSnapshot.exists()) {
throw ResourceNotFoundException("Oops!")
}
offer(documentSnapshot.toObject(PrintOrder::class.java))
} catch (e: Exception) {
close(e) // close the flow with a non-null cause
}
}
With this, you should be able to catch exceptions as your firebaseFireStoreException, ResourceNotFoundException or any other one inside the catch operator because the flow is now completed exceptionally.
I have a HTML5 worker which sends values with postMessage. Sometimes (for example if the result is a function) the code throws an exception:
DataCloneError: The object could not be cloned.
So I tried to catch the exception:
try {
self.postMessage (result);
}
catch (ex) {
if (ex instanceof DataCloneError)
self.postMessage (result.toString());
else
throw ex;
}
But this throws the following exception:
ReferenceError: DataCloneError is not defined
I am confused. How to catch the DataCloneError?
The error you receive is an instance of the DOMException interface.
To know which DOMException it is, you can check its name property.
The one of DATA_CLONE_ERROR, is "DataCloneError".
try {
postMessage( () => {} , '*' );
}
catch( err ) {
console.log( err.name === "DataCloneError" );
}
I'm using Nancy to create a web api. I have a signed token that is passed in from the user to authenticate. This authentication is doen in the RequestStartup method in my own Bootstrapper. Now in some cases, for instance when I can't veryfy the signed token I would like to just be able to throw an exception and have that handled byt the OnError hanhdler in Nancy. However an exception thrown before the RequestStartup is finsihed isn't caught. The request generates a 500 error and I would like to return something else with my own error information.
I have the obvious case where I throw an exception but also possibilities of an exception being thrown in the GetIdentity() method.
I'm looking for any input in how to handle this.
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
base.RequestStartup(container, pipelines, context);
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) =>
container.Resolve<IErrorHandler>().HandleException(ctx, exception));
var identity = container.Resolve<IAuthenticationController>().GetIdentity();
var configuration = new StatelessAuthenticationConfiguration(_ => identity);
StatelessAuthentication.Enable(pipelines, configuration);
var logManager = new LogManager(context);
pipelines.AfterRequest.AddItemToEndOfPipeline(_ => logManager.Log());
try
{
X509Certificate2 clientCert = context.Request.ClientCertificate as X509Certificate2;
container.Resolve<ICertificateValidator>().Validate(clientCert);
}
catch (Exception ex)
{
throw new MklServerAuthenticationException(ErrorCodes.WrongOrNonexistingCertificate, ex);
}
}
Figured out a way to solve the above problem and thought somebody else might like to know. Replace the line in my code above, containing the GetIdentity() call, with the following:
Identity identity = null;
try
{
identity = container.Resolve<IAuthenticationController>().GetIdentity(requestInfo);
}
catch (Exception ex)
{
var exception = new MklAuthentcationException(ErrorCodes.TokenInvalid, ex);
context.Response = container.Resolve<IErrorHandler>().HandleException(context, exception);
pipelines.BeforeRequest.Invoke(context, CancellationToken.None);
}
I'm using the fact stated in nancy that:
The PreRequest hook is called prior to processing a request. If a hook returns a non-null response then processing is aborted and the response provided is returned.
So by setting a response (my error in this case) on the PreRequest hook and invoking it my error is returned and execution is stopped.
Maybe not the nicest solution... If you can figure out something better please let me know.
I am trowing Exception from WebApi as shown below
Catch(ex)
{
var rEx = HttpResponseException(r.CreateErrorResponse(HttpStatusCode.NotFound,ex));
throw rEx;
}
My question is "How to catch this Exception in Windows Application";
i.e. to catch this exception from where I am calling Web Api Method????
You will receive response with http code 500 - internal server code. So, to "catch" this exception just check response code in calling app.
That would throw a 404 response back to the client. Assuming you're using WebClient to call this service, it can be done in a couple of ways:
1) You can check for the status of the response like this:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
//write app code.
}
2) Or.. in a try/catch fashion by checking: resp.EnsureSuccessStatusCode(), which would throw an exception if the response is not 200. Like this:
try
{
HttpResponseMessage response = await client.GetAsync("api/products/1");
resp.EnsureSuccessStatusCode(); // Throw if not a success code.
// ...
}
catch (HttpRequestException e)
{
// Handle exception.
}
It is discussed in detail here