For most of the errors in Mulesoft there is no error code defined. If it doesn't know, Mule flatly prints MULE_ERROR--2. Instead of this I want to put in my own error code which will be fetched from DB and include it in the exception payload. After this, the exception payload should be sent to a handler flow for re-submission based on error code. Hence in error handling part of the flow I need to have more than one component.
Tried Custom Exception Strategy, Catch Exception Strategy, Using Java component and flow-refs but none of them worked.
Also, I built a dummy code for this (without fetching the error code) to put my own custom error msg and what I noticed is, it throws the same error twice, once by default for the first time and again when I put my error msg and throw the error. To suppress this I put
<AsyncLogger name="org.mule.exception.CatchMessagingExceptionStrategy" level="FATAL"/>
in log4j2.xml.
Will this cause any issues?
You can always define your own Errors and customise it. Follow below link for further information,
http://blogs.mulesoft.com/dev/api-dev/api-best-practices-response-handling/
Below is the content for the same :
Use HTTP Status Codes
One of the most commonly misused HTTP Status Codes is 200 – ok or the request was successful. Surprisingly, you’ll find that a lot of APIs use 200 when creating an object (status code 201), or even when the response fails:
invalid200
In the above case, if the developer is solely relying on the status code to see if the request was successful, the program will continue on not realizing that the request failed, and that it did something wrong. This is especially important if there are dependencies within the program on that record existing. Instead, the correct status code to use would have been 400 to indicate a “Bad Request.”
By using the correct status codes, developers can quickly see what is happening with the application and do a “quick check” for errors without having to rely on the body’s response.
You can find a full list of status codes in the HTTP/1.1 RFC, but just for a quick reference, here are some of the most commonly used Status Codes for RESTful APIs:
200 Ok
201 Created
304 Not Modified
400 Bad Request
401 Not Authorized
403 Forbidden
404 Page/ Resource Not Found
405 Method Not Allowed
415 Unsupported Media Type
500 Internal Server Error
Of course, if you feel like being really creative, you can always take advantage of status code:
418 I’m a Teapot
It’s important to note that Twitter’s famed 420 status code – Enhance Your Calm, is not really a standardized response, and you should probably just stick to status code 429 for too many requests instead.
Use Descriptive Error Messages
Again, status codes help developers quickly identify the result of their call, allowing for quick success and failure checks. But in the event of a failure, it’s also important to make sure the developer understands WHY the call failed. This is especially crucial to the initial integration of your API (remember, the easier your API is to integrate, the more likely people are to use it), as well as general maintenance when bugs or other issues come up.
You’ll want your error body to be well formed, and descriptive. This means telling the developer what happened, why it happened, and most importantly – how to fix it. You should avoid using generic or non-descriptive error messages such as:
redx Your request could not be completed
redx An error occurred
redx Invalid request
Generic error messages are one of the biggest hinderances to API integration as developers may struggle for hours trying to figure out why the call is failing, even misinterpreting the intent of the error message altogether. And eventually, if they can’t figure it out, they may stop trying altogether.
For example, I struggled for about 30 minutes with one API trying to figure out why I was getting a “This call is not allowed” error response. After repeatedly reformatting my request and trying different approaches, I finally called support (in an extremely frustrated mood) only to find out it was referring to my access token, which just so happened to be one letter off due to my inability to copy and paste such things.
Just the same, an “Invalid Access Token” response would have saved me a ton of hassle, and from feeling like a complete idiot while on the line with support. It would have also saved them valuable time working on real bugs, instead of trying to troubleshoot the most basic of steps (btw – whenever I get an error the key and token are the first things I check now).
Here are some more examples of descriptive error messages:
greencheckmark Your API Key is Invalid, Generate a Valid API Key at http://…
greencheckmark A User ID is required for this action. Read more at http://…
greencheckmark Your JSON was not properly formed. See example JSON here: http://…
But you can go even further, remember- you’ll want to tell the developer what happened, why it happened, and how to fix it. One of the best ways to do that is by responding with a standardized error format that returns a code (for support reference), the description of what happened, and a link to the appropriate documentation so that they can learn more/ fix it:
{
"error" : {
"code" : "e3526",
"message" : "Missing UserID",
"description" : "A UserID is required to edit a user.",
"link" : "http://docs.mysite.com/errors/e3526/"
}
}
On a support and development side, by doing this you can also track the hits to these pages to see what areas tend to be more troublesome for your users – allowing you to provide even better documentation/ build a better API.
Related
I have a basic SOAP based web service. I am able to invoke methods and add information to it. But, while retrieving , the data a single class object seems to be perfectly displayed in the WSE browser. But If I have a list of objects, then I am not able to get any response in the body. Not sure, whats going wrong. Even the logs in console don't throw any error.
IS there a better way to view list of objects in WSE ?
Try clicking the Source link (to the right of the body) to check if the SOAP Response Envelope indeed has multiple objects in it. If it has, you may have encountered a bug in the viewer, if it doesn't - either the service doesn't work as expected, or your Request is not proper.
I tested locally with the following public service (operation getAll):
http://www.predic8.com:8080/crm/CustomerService?wsdl
It returns a list of many customers (judging from the raw response), but for me WSE only listed a few of the them (and the indentation depicting the hierarchy is wrong), so I guess this view of WSE is not very reliable.
So I'd suggest sticking to the raw XML view in WSE. In my everyday work I prefer using SOAP UI for service exploring/testing. It is free and gets regularly updated - you might want to check it out.
Good luck!
I need a java code to use wikipedia api. I would like to get the tags of a specific value on wikipedia (the tags that appear at the end of the page). I know that the api call I need is
"http://en.wikipedia.org/w/api.php?action=query&format=json&titles=Albert%20Einstein&prop=categories"
(for the example of Albert Einstein)
But I find it difficult to understand from the MediaWiki API documentation page if I need a token and hash, or to log in or not. I know that sometimes it is not necessary to log in.
Right now my code is:
JSONArray wikiResult=null;
String url1= "http://en.wikipedia.org/w/api.php?action=query&format=json&titles=Albert%20Einstein&prop=categories";
wikiResult=ApiCall(url1);
where ApiCall is a function that sends the call, and it works fine, I have checked it.
the JSONArray returned is empty.
Can somebody please tell me what I'm doing wrong?
You don't need to log in or get token for prop=categories.
The actual error is probably explained in the response. It's possible that you're getting an empty result, because the response is not JSON (that happens with some errors).
If I were to guess, I think you're not setting the User-Agent header in your request, which is required by Wikimedia wikis.
I have my program working and all done (java). It's a short and easy program for a job interview. I handle stuff like improper input format by throwing a custom exception. Is that the best way to do it or should I just make a print statement?
Exceptions are only useful if they will be handled by other code.
If you're writing a reusable library, you should by all means throw an exception.
There is nothing more frustrating than calling a third-party library that logs errors to the console instead of telling your code about them.
However, if you're writing a standalone utility, it's nicer to print friendly error messages than an ugly stack trace.
The most flexible approach is to write reusable code that throws exceptions, then add catch blocks in main() (or elsewhere in the standalone portion) that prints friendly messages.
If you handle improper format inline is the code readable? If so - fine, if not - throw an exception and handle it elsewhere
Are you able to handle improper format properly in the place you are parsing it or maybe some more generic method/class/module is actually calling your routine and should decide what to do? If the latter is the case -> throw an exception
In general - it depends. If you can handle this special situation "inline" - you can do it (make sure it's readable). If not - throw an exception.
Here's a good reference on exception best practices. You should make sure you are following these.
In your particular case (based on the details you have provided) a user may upload/select a file that has bad data. You program should handle that by catching any basic Java runtime issues and returning information to the user (not "Exception in thread..." but something more readable to a user). If you are checking for these alpha characters then you should just handle that (with an error to the user) without throwing an exception - unless this is truly the behavior you want.
Exception are cause when the program cannot work in a normally correct manner.
The exceptions get more complicated and increase in numbers when you evolve from j2se to j2ee.
For a stand alone application
If your application is just a extremely simple calculator then you may just completely forget about exception because your user input would be filtered and one of the few exception would be division by zero
If your application is a simple utility tool say screen capture , then if your file cannot be saved (exception at file i/o) then all you need to do is simply terminate all your task and say some error message to the user.
For an advanced project of example 2 , you need to save the image in a temp , and perform saving of file once the issue is rectified
For a enterprise scaled and distributed application
Here transaction(inter related activities) is involved . Here a simple message to the user is also needed at times and also handle(do needed changes to related transactions) the exception !
If the application is distributed in many countries then exception in one traction needs alteration in another server in another country , this demands optional incorporation of a some thing that uses JMS API(message sending inside application)
JPA (java persistence api) implicitly rolls back the database on event of a exception and provides facility to do so for interrelated transactions . But still the roll back only affects the database and not the instance variable(object values)
and at all times you don't want to user to read your exact stack trace that says error at line number .....
I worked on a website in China last year. THe website has been running fine, but I just received an email fromNetwork Security Bureau in China.
They sent me an attachment along with a few URLs. one of them is
http://mydomain.com/servlets/pdf?var=xss<audio src=pksovf onerror=pksovf(qrx)>
They say that the above url has a risk. I checked the url and it throws 500 error all the time because the url format is incorrect.
if a page throws a 500 error, is there still a risk? I don't think so, but I just want to confirm.
A 500 is roughly analogous to a crash in a piece of desktop software. Crashes are considered security risks because they can be exploited by malicious inputs, and the same could be said of the web server.
A 500 means "something we weren't expecting happened, and we failed to deal with it." That means there's something there that could be exploited - there's no guarantee of that, just like there's no guarantee that a crash in a piece of desktop software can be exploited, but it's correct to treat both of those cases as potential security holes.
Potentially yes. It depends where the error occured.
If your back-end did inserted this string in a database somewhere before crashing, that may be queried later on to render this string in one of your view, this could be dramatically dangerous as an attacker could potentially insert arbitrary HTML or Javascript in a webpage and redirect for exemple a user to a harmful website.
Also, this could easily result in an SQL injection if a database was queried with this string at some point, given that it was not filtered.
To summarize, it depends on what your did with this string and where did your code crash.
Anyway, you should not have this kind of issues and should always check the validity of a user input. Getting a 500 HTTP return code is exceptional and means that something went wrong on the server side. You got to fix this anyway.
My current problem is very similar to this one.
I have a downloadFile(URL) function that creates a new HttpURLConnection, opens it, reads it, returns the results. When I call this function on the same URL multiple times, the second time around it almost always returns a response code of -1 (But throws no exception!!!).
The top answer in that question is very helpful, but there are a few things I'm trying to understand.
So, if setting http.keepAlive to false solves the problem, it indicates what exactly? That the server is responding in a way that violates the http protocol? Or more likely, my code is violating the protocol in some way? What will the trace tell me? What should I look for?
And what's the deal with this:
You need to read everything from error
stream. Otherwise, it's going to
confuse next connection and that's the
cause of -1.
Does this mean if the response is some type of error (which would be what response code(s)?), the stream HAS to be fully read? Also, every time I am attempting an http request I am basically creating a new connection, and then disconnect()ing it at the end.
However, in my case I'm not getting a 401 or whatever. It's always a 200. But my second connection almost always fails. Does this mean there's some other data I should be reading that I'm not (in a similar manner that the error stream must be fully read)?
Please help shed some light on this? I feel like there's some fundamental http protocol understanding I'm missing.
PS If I were just using the Apache HttpClient, would I not have to deal with all these protocol details? Does it take care of everything for me?
The support for keep-alive in the default HTTP URL handler is very buggy. We always turn it off.
Use Apache HttpClient with a pooled connection manager if you want keep-alive. If you don't want change your code, you can get another handler like this one,
http://www.innovation.ch/java/HTTPClient/
If your second connection always fails, that means your server doesn't support keepalive. With Keepalive, the HTTP handler simply leaves connection open (even if you call disconnect). The server closes connection if keep-alive is not supported but the handler doesn't know till you make next request on the connection so the 2nd connection fails.
Regarding the read error stream, it only applies if you get non-200 responses.
i think you're probably talking about this HttpURLConnection bug, fixed in froyo:
http://code.google.com/p/android/issues/detail?id=2939
see that bug for other workarounds. if this isn't the bug you've hit, please raise a bug with a repeatable test case at http://code.google.com/p/android/issues/entry.