Accessing ResourceException in Eclipse? - eclipse-plugin

I'm doing something in an Eclipse plugin that throws a ResourceException. I in turn need to know what the path of the resource involved is.
I can do this via ((ResourceStatus) caughtException.getStatus()).getPath() , however I then get admonished with Discouraged access: The type 'ResourceException' is not API (same warning for ResourceStatus). Should I just ignore the warning, or is there a better way for me to get the path? I'm just worried that this might change later on.
Technically I could extract the path from the exception's message, but that feels gross & have back luck with scraping data out of human-presentable strings :-/

ResourceException extends CoreException which is part of the official API so you can catch that.
ResourceStatus implements IResourceStatus which again is an official API.
So something like:
catch (CoreException ex) {
IStatus status = ex.getStatus();
if (status instanceof IResourceStatus) {
IPath path = ((IResourceStatus)status).getPath();
....
}
}
IResourceStatus also contains the definitions of the error codes that IStatus.getCode returns for a resource exception.

Related

How to show firebase auth error messages different in UI

I am using the firebase auth now I want to show a different message in UI for every error message
You have to check for specific error messages in your catch block and add custom handling.
You don't mention the language you're working in (and I'm not familiar with all of the different libraries), but C# will throw a FirebaseAuthException containing the property AuthErrorCode which is an enum representing the error. You could check that in, say, a switch statement to get the required message.
try {
userRecord = await _FirebaseAuth.GetUserByEmailAsync(email, token)
.ConfigureAwait(false);
}
catch (FirebaseAuthException ex) {
if (ex.AuthErrorCode == AuthErrorCode.UserNotFound) {
DisplayError($"Error retrieving user record for {email}");
}
}

Sleuth/zipkin with ControllerAdvice is not working

I found there is an old issue Sleuth/Zipkin tracing with #ControllerAdvice, but I meet the same problem with the latest version(spring-cloud-starter-zipkin:2.1.0.RELEASE), I debug it and find that the error is null, so zipkin just guess with statuscode. I have to throw the exception again to make zipkin notify the exception
error is null
zipkin result
ControllerAdvice
throw the exception again, it works
It makes perfect sense that it's null. That's because YOU control the way what happens with the caught exception. In your case, nothing, cause you swallow that exception.
If you want to do sth better, just add the error tag manually via the SpanCustomizer. That way you'll add the exception to the given span. It will then automatically get closed and reported to Zipkin (you can do sth else than ex.toString() of course.
#Slf4j
#RestControllerAdvice
#Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionHanders {
private final SpanCustomizer customizer;
public ExceptionHanders(SpanCustomizer customizer) {
this.customizer = customizer;
}
#ExceptionHandler({RuntimeException.class})
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleRuntimeException(Exception ex) throws Exception {
this.customizer.tag("error", ex.toString());
return "testabcd";
}
}

Proper way to send Web API response

I read somewhere that TRY CATCH is not recommended in Web API methods.
I'm making the following call into a method and if all goes well, I want to return an Employee object along with Status 200 but if something goes wrong e.g. database call fails, etc. I want to return status 500. What's the right way to handle that code?
[HttpPost]
public async Task<IHttpActionResult> PostNewEmployeeAsync(Employee emp)
{
var newEmployee = await RegisterEmployee(emp);
return Ok(emp);
// What if I had a database error in RegisterEmployee method. How do I detect the error and send InternalServerError()
}
private async Task<Employee> RegisterEmployee(Employee emp)
{
// Call DB to register new employee, then return Employee object
}
Your code should return the error code that matches the case that you have, for example if your code couldn't find the required resource in the database return NotFound,
but if you code raises an exception, avoid wrapping your code by try/catch block and instead the exception should bubble up to the level that you can handle it globally, to do this you have many options like :
1- Implement an ExceptionFilter where you can handle all the unhandled exceptions raised in your controllers (this doesn't include any exception happens before the controllers in the pipeline).
See this for more details about ExceptionFilterAttribute.
2- If you are using Web API 2, you can implement the interface IExceptionHandler where you can handle all the exception happens anywhere in the pipeline and there you can return the errors you want.
See this for more details about Global Exception Handling in Web API 2.
Hope that helps.
You don't want to avoid try/catch entirely, you just need to be really careful about it. Wrap your code in a try block, and catch the exception you're expecting. Inside the catch, return the error response.

Exception handling in Controller in ASP.Net MVC 4 with ELMAH and ajax

I've seen a number of posts and articles but am not able to see the solution crisply.
I've installed Elmah.MVC via NuGet and have commented out this line from FilterConfig.cs:
//filters.Add(new HandleErrorAttribute());
So that Elmah would pick up the errors.
It works when I provide an invalid action name and I get a yellow page as well as an email.
I want to know about two other types of errors that my code may generate... how are we supposed to handle them:
1.E.g. if my repository or manager (business logic) layer throws an exception when trying to access database or send an email etc.
a. Is the correct way to NOT implement any kind of try catch in Controllers (or anywhere else for that matter) and let Elmah take care of exceptions?
b. If so, and if it shows a yellow error page, how can we show a view of our own liking?
2.If my view contains ajax calls, e.g. via jqgrid, and behind the scenes there are errors, I've noticed they also get picked up properly by Elmah. But how do I show some kind of an error message to the user as well?
Thanks
Here is what I did:
In controller, I placed try catch:
try
{
//model = getmodelfromdb();
return View("MyView", model);
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return View("../Error/ShowException", ex);
}
For custom view for 404, I did this in global.asax:
protected void Application_OnError( )
{
var exception = Server.GetLastError( );
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
Helper.SetSessionValue(SessionKeys.EXCEPTION, exception);
Response.Redirect( "~/Error/ShowException");
}
For jqgrid, I did this in my controller:
[HttpPost]
public ActionResult ListRecords( int page , DateTime? fromdate , DateTime? todate)
{
try
{
var list = FetchListFromDB();
var result = new
{
total = Math.Ceiling(list.Count / (decimal)Helper.PAGE_SIZE),
page = page, //--- current page
records = list.Count, //--- total items
rows = list.List.Select(x => new
{
id = x.EntityID,
cell = new string[]
{
x.Property1,
x.Property2
}
}).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var result = new
{
errorMessage = "An unexpected error occurred while fetching data. An automatic email has been generated for the support team who will address this issue shortly. Details: " + ex.Message,
records = 0
};
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return Json(result, JsonRequestBehavior.AllowGet);
}
And this in the View (in the jqgrid definition):
loadComplete:function(data)
{
if (data.errorMessage)
{
alert(data.errorMessage);
}
},
In a general ajax scenario:
success: function(data)
{
if (data.errorMessage)
{
alert(data.errorMessage);
}
else
{
//...
}
},
a. Is the correct way to NOT implement any kind of try catch in Controllers (or anywhere else for that matter) and let Elmah take care of exceptions?
I'd say that Elmah doesn't "take care" of exceptions, it records them. Ideally, you should try to handle the errors - by all means log them, but also add logic to deal with them so that they don't interrupt the user's workflow.
I'd wrap logic in try blocks, and in the catch use
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
to record anything that goes wrong. Immediately after that line, however, I'd then do something to try to recover from the exception - catch specific exception types, never just catch (Exception e), and deal with them after logging them. The idea is that you should be reviewing your logs, working out what's causing the exceptions, and improving your program so that it doesn't throw exceptions any more.
To show your own error pages, there's the HandleErrorAttribute, or if you don't want to use that there's also the controller's OnException() method, which is called when a controller action method quits with an exception rather than finishing normally. An ExceptionContext object is passed into that method, so you can use that to get the exception that was thrown and log it, do any cleanup that might be required etc.
I know i'm very late to the party but I stumbled upon this answer while searching something similar form Google.
I don't like using try catch blocks everywhere in my code, especially in web apps. I let Elmah catch everything and log it behind the scenes. Then in the web.config file you can redirect based on the error type...
<customErrors mode="RemoteOnly" defaultRedirect="~/Error" >
<error statusCode="500" redirect="~/Error"/>
<error statusCode="404" redirect="~/NotFound"/>
</customErrors>

AXIS Client v.s. AXIS2 Service

I must implement an AXIS 1.4 client which consume an AXIS2 1.4 method. AXIS 1.4 client is made by creating the stubs. The client send a request and get back a response from service with some attachment (MTOM). When I call the method (operation) by AXIS 1.4 port type object I got an error:
org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.
I think MTOM messed up with AXIS. So here is the question: how did I get the attachment the AXIS2 1.4 (MTOM) web service return me back? TIA.
Francesco
P.S: here is the code. There are stubs generated by WSDL. The problem is: i get the exception when I call the port's stub method. There are attachments in the message I get back.
String codistat = "CODISTAT";
OrdinanzeViabilitaLocator ovlocretreive = new OrdinanzeViabilitaLocator();
ovlocretreive.setOrdinanzeViabilitaHttpSoap11EndpointEndpointAddress(".. the service url + action..");
try {
OrdinanzeViabilitaPortType ovretreive = ovlocretreive.getOrdinanzeViabilitaHttpSoap11Endpoint();
((Stub) ovretreive)._setProperty(javax.xml.rpc.Call.USERNAME_PROPERTY, "username");
((Stub) ovretreive)._setProperty(javax.xml.rpc.Call.PASSWORD_PROPERTY, "password");
//problems began here
MessageReqOrdinanze mrq = new MessageReqOrdinanze();
mrq.setCodistat(codistat);
Calendar date_from = Calendar.getInstance();
date_from.setTimeInMillis(0);
Calendar date_to = Calendar.getInstance();
date_from.setTimeInMillis(0);
mrq.setDate_from(date_from);
mrq.setDate_to(date_to);
// the next line generate the exception
MessageOrdinanze mretreive = ovretreive.getOrdinanze(mrq);
} catch (AxisFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
The message I get back has a
<xop:include href="cid... >...< ../xop/include"/>
tag inside, it's MTOM (it cause the exception I guess).
Hope this helps.
There are two things that need to be done to make MTOM work on the client side:
Ensure that in the stubs, the xs:base64Binary type is mapped to java.activation.DataHandler instead of byte[].
Set up a (runtime) type mapping for xs:base64Binary and java.activation.DataHandler that uses JAFDataHandlerSerializer and JAFDataHandlerDeserializer (which support MTOM).
The second part is fairly easy. Simply set up a client-config.wsddfile with the following type mapping:
<typeMapping languageSpecificType="java:javax.activation.DataHandler" qname="xs:base64Binary"
deserializer="org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory"
serializer="org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory"
encodingStyle=""/>
The first part is more tricky because the tooling (wsdl2java) in Axis 1.4 doesn't support changing the Java type associated with a given XML type. There are several ways to work around that limitation:
Edit the generated stubs by hand and change byte[] to javax.activation.DataHandler. Depending on how you manage generated code in your project, that may or may not be an acceptable solution.
It is probably possible (although I didn't test that) to trick wsdl2java into using javax.activation.DataHandler by giving it a modified WSDL where the type {http://www.w3.org/2001/XMLSchema}base64Binary is replaced by {java}javax.activation.DataHandler.
I fixed the tooling in the current Axis trunk so that it supports this type of configuration. Note however that this is only implemented in the wsdl2java Maven plugin (but not in the Ant task or the command line tool). You could use the 1.4.1-SNAPSHOT version of that plugin; the generated code would still work with Axis 1.4. You can find some documentation here.
Above solution is great. However those who might be struggling to make above code snippet work, please use xmlns:xs="http://www.w3.org/2001/XMLSchema", then only given typeMapping snippet works.
<typeMapping qname="xs:base64Binary" languageSpecificType="java:javax.activation.DataHandler"
deserializer="org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory"
serializer="org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory"
xmlns:xs="http://www.w3.org/2001/XMLSchema" encodingStyle="" />