RestTemplate - Handle custom error message - rest

I have Restful API that responds 404 errors when an item is not found, but have different messages depending on the reason why the item is not found (unknown, not available, ...), it is done this way using Spring MVC :
response.sendError(HttpServletResponse.SC_NOT_FOUND, "NOT_AVAILABLE");
(this works fine with any browser, displaying 404 errors with "NOT_AVAILABLE" as message)
Now, I'd like to get that message back into my Java code using Spring RestTemplate in order to manage them.
I tried this:
try {
rest.put(apiRootUrl + "/item/{itemId}", null, itemId);
} catch (HttpClientErrorException e) {
if (NOT_FOUND == e.getStatusCode()) {
switch (MyErrorCode.valueOf(e.getStatusText())) {
case NOT_AVAILABLE:
return displayNotAvailableError();
case UNKNOWN:
return displayUnknownError();
default:
// ...
}
}
}
but in the getStatusText(), I always got the NOT FOUND label (from 404) and not my custom value.
Does someone know if it is possible to retrieve the custom message from 404 errors? And therefore how?
thanks a lot!
Edit: I run on a Tomcat server (which sends the 404 HTML page) and this does not append with a Weblogic server

OK, after digging a bit more, the solution is in fact very simple !
Tomcat was sending back to me its default 404 page, I just needed to tell it to use mine!
How to do this:
create a 404.jsp page like this:
<%# page pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${requestScope['javax.servlet.error.message']}"/>
reference it in your web.xml
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
And now, you can get the message in your client using e.getStatusText()

Related

how to send the domain instance back to the client in case of Grails validation errors

I just started to learn Grails and my question of this could be dumb. So apologies if it is dumb. I have a client program and a REST web service - both coded by me. The client program calls the RESTful service using POST (to add record to a database). When I call object.save() there are some validation errors that are returned.
In my gsp I have fieldError tag coded to read the error message for each field in the bean and show it in the screen. I'm assuming I needed to pass the domain instance that failed the validation from RESTful service to the client so the client could inturn send it to gsp which will automatically show errors. Correct me if this is wrong. however I don't know how to pass the domain instance object as XML from the web service. When the validations are successful though, I get the object like "render object as XML". However when validations fail, I don't know how to pass the entire failed domain instance object back as xml.
I tried to code,
if (student.save()){
render student as XML
} else {
student.errors.each(){
println it
}
def errmsg = student.errors.allErrors.collect { g.message(error:it) }
render(contentType:"text/xml") {
respstud {
for(err in errmsg) {
message(err)
}
}
}
}
This returned the specific error message back to the client as xml, but I'm needing the entire student object to be sent back to the client when save() fails also. Can someone please help?
let me know if you need more info. This is my first post in stackoverflow so I don't really know if I have to provide more details. Any help is greatly appreciated.
Thanks,
Prem
Because the request is being made via ajax, you will need to handle it the Ajax way.
Your gsp is compiled on the server and sent as html to the client when the page is first requested.
One way to handle this would be to set an error on the ajax response and return a snippet of the code you would like to render.
The response may then be handled in the error section of your calling JavaScript and the code snippet rendered on the page where you wish.

Unable to redirect from sharepoint event receiver

I have created an event receiver on the "Task" list.
If the "Due Date" is null then the user should be redirected to the custom error page.
Custom error page resides in the SharePoint mapped folder under "Layouts" directory.
The event receiver code is as follows:
public override void ItemAdding(SPItemEventProperties properties)
{
try
{
if (properties.AfterProperties["Due Date"] == null)
{
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "_layouts/CustomErrorPage/DueDateErrorPage.aspx";
}
}
catch (Exception ex)
{
}
}
The custom error page which is of type "Application Page" having name. "DueDateErrorPage.aspx". The mark up is:
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
ERROR : You cannot create the task without due date
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Custom Error Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Custom Error Page
</asp:Content>
Though in IIS, under the _layouts direcory the page is available I am getting this output.
How should I tackle this error? Please help.
I think your redirect url is invalid, because it will be relative to the current page, and not the current site or site collection.
You can diagnose this by looking at the dialog frame properties, and check the url.
Method 1 : solve the amgiguity
To resolve ambiguity, I suggest you to use the SPUtility.GetServerRelativeUrlFromPrefixedUrl method.
This will create a correct url.
Especially, change your code like this:
properties.RedirectUrl = SPUtility.GetServerRelativeUrlFromPrefixedUrl(
"~site/_layouts/CustomErrorPage/DueDateErrorPage.aspx"
);
This will dynamically resolve ~site to your current SPWeb url. You can also use ~sitecollection to resolve the site collection.
Method 2: make the field mandatory
Why don't you simply make the due date mandatory?
Method 3: use the standard sharepoint error page (not tested I admit)
Instead of redirecting to your own page, "Cancel" the event with a custom error message:
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage= "Due date is mandatory";
Moreover, CancelWithRedirectUrl is now obsolete.
PS: as a side note, you should know that a SharePoint dedicated Stack Exchange site exists.
First of all I first checked the url in web browser that is:
/_layouts/CustomErrorPage/DueDateErrorPage.aspx
It was opening the page that means the page is available but there is something missing in the url only.
So by using the SPUrlUtility class I was able to redirect the page.
The changes I needed to made was:
properties.RedirectUrl = SPUrlUtility.CombineUrl(properties.WebUrl,"/_layouts/CustomErrorPage/DueDateErrorPage.aspx");
It's working perfectly..

No submit request sent out by GWT file upload

GWT 2.5.0 DevMode
I had a simple test on file upload below,
startupUrl: http://127.0.0.1:8888/UploadTest.html?gwt.codesvr=127.0.0.1:9997
<g:FormPanel ui:field="fpUpload">
<g:VerticalPanel>
<g:FileUpload name="fileData" ui:field="fuUpload" />
<g:Button ui:field="btUpload">Upload</g:Button>
</g:VerticalPanel>
</g:FormPanel>
#UiHandler("btUpload")
public void onClickUploadButton(ClickEvent e) {
System.out.println("fileName:" + fuUpload.getFilename());
fpUpload.setEncoding(FormPanel.ENCODING_MULTIPART);
fpUpload.setMethod(FormPanel.METHOD_POST);
fpUpload.setAction("/files");
fpUpload.submit();
System.out.println("Submitted, please wait!");
}
#UiHandler("fpUpload")
public void onSubmitComplete(SubmitCompleteEvent event) {
System.out.println("Submit completed!");
}
Output:
fileName:C:\fakepath\one_file_chosen_to_upload
Submitted, please wait!
However, the server didn't receive the submit request, so "Submit completed!" never appeared.
Meanwhile, the traffic was snooped below, the submit request didn't send out at all.
$ tcpdump -A -i lo port 8888
No exceptions were thrown, too. Any idea?
#EDIT
The problem is reproducible on ProdMode.
#EDIT 2
After merely rebooting the machine, now the problem seems gone just as silently as the http submit request was ignored to emit over the wire. Unfortunately, i have no clues why.
It seems you have not coded an appropriate servlet to handle the multipart request, also you have to configure that servlet in your web.xml. Could you add to your question your servlet code and the content of your web.xml ?
Note that onSubmitComplete is not executed if the server return a 404. Try to inspect the server response with Firebug, or change the form action by any thing so as you get the same failure.
FYI, there is a ibrary: gwtupload which is very easy to use and is plenty of nice features, maybe you could take a look to theirs example page and give a try.

What event to hook to redirect on 404 errors? Symfony 1.4

I am using symfony 1.4.
I need to redirect certain urls when 404 error occurs.
Let's say user is looking for a url http://example.com/oldurl and it doesn't exist I want to check if this url is set for redirect.
If url is set to be redirected I would like to redirect it to that url.
QUESTION: Which event should I hook into to get info about the requested url, that got redirected to 404 error page ?
P.S We only want to check for redirection if page doesn't exist. We do not want to run "the check" for every request, only when page not found!
thanks a lot!
Symfony fire an event each time a page is not found: controller.page_not_found.
You can find it in the documentation: http://www.symfony-project.org/reference/1_4/en/15-Events#chapter_15_sub_controller_page_not_found
Edit:
You can retrieve the url in the method that listen to this event by calling the context. With something like that:
$context = sfContext::hasInstance() ? sfContext::getInstance() : null;
if(null !== $context)
{
$requested_url = $context->getRequest()->getUri();
}
You can give a closer look to the plugin sfErrorNotifierPlugin, it catches exception and 404 error and send an email for a report. Look at how they handle 404 error.
I don't know where to hook exactly inside the execution stack, but I know the general cleaner way through routing. If you are doing routing without still having in code the default routing rule (which you shouldn't by practice since), then it would be as simple as the following in your app routing.yml (at the end):
catch_all:
url: /*
param: { module: yourModule, action: handleNotFound }

How to stay in same page when executing a Server request in a portlet

I am calling a webpage from a portlet. The webpage is a form for user to enter data and has a button which submits the user data into Database.
But the Button also redirects the portlet site to the webpage through the proxy Gateway.
How to stay in the same portlet page while having the Form data submitted to the database?
You could use AJAX
Just adding to the AJAX answer..
A standard JSR 286 portlet supports such asynchronous action through serveResource method in the portlet class, which you'll need to override.
In the java file,
public void serveResource(ResourceRequest request, ResourceResponse response)
throws PortletException, IOException {
//Write or invoke your database code here...
}
Also, in the html <form> tag you will need to set <portlet:resourceURL> in the action attribute.
Hope this helps, even though I am assuming by portlet you mean Java portlets and not something else