How to handle Code Error 500 in Richfaces - jsf

I'm using Richfaces 3.2.2 and need to show the user the 500 error page when there is Exception. The issue is that when I use ajax event I can't show the user the 500 error when there is an Exception. I've already defined the error page on web.xml.
Excuse My English. Any suggestion please ?

Check the RichFaces developer guide chapter 5.10.1.
5.10.1 Request Errors Handling
To execute your own code on the client in case of an error during Ajax request, it's necessary to redefine the standard "A4J.AJAX.onError" method:
A4J.AJAX.onError = function(req, status, message){
window.alert("Custom onError handler "+message);
}
The function defined this way accepts as parameters:
req - a params string of a request that calls an error
status - the number of an error returned by the server
message - a default message for the given error
Thus, it's possible to create your own handler that is called on timeouts, internal server errors, and etc.
So, to display the server-generated error response, you'd like to do the following:
A4J.AJAX.onError = function(req, status, message){
document.open();
document.write(req.responseText);
document.close();
}
To redirect to the error page, do as follows:
A4J.AJAX.onError = function(req, status, message){
window.location = 'error.jsf';
}
You'll only need to pass mandatory error details as request parameter or let the server side store it in the session as Odelya suggested.
Related question:
Handling of HTTP 4nn/5nn errors in jQuery's ajax requests

Since you are using probably JSF1.2 and not JSF2, you can use FaceletViewHandler to handle the exceptions.
public class CustomViewHandler extends FaceletViewHandler {
...
#Override
protected void handleRenderException(FacesContext context, Exception ex) throws IOException, ELException,
FacesException {
try {
..
getSessionMap().put("GLOBAL_ERROR", ex);
getHttpResponseObject().sendRedirect("/error.jsf");
} catch (IOException e) {
log.fatal("Couldn't redirect to error page", e);
}
}
}
of course, you need to handle it in the bean, just extract the exception from session:
Throwable ex = (Exception) getSessionMap().remove("GLOBAL_ERROR");

Related

Servicestack Display 404 page CatchAllHandlers

Im using servicestack Core with kestrel. I made a CatchAllHandlers delegate with the following code.
var requestType = typeof(NotFoundPage);
var restPath = new RestPath(requestType, pathInfo);
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
But the problem is that my ServicestackApi now is no longer reachable, url: /json/reply/GetApiCall goes to the 404 not found page.
Is there a way to solve this? can i check if its an api call or can i go later in the pipeline to handle the request?
update
I found that if i remove CatchAllHandler and just add the next middleware this middleware is called:
app.Use((context, next) =>
{
context.Response.Body.Write("yaayaya");
return Task.CompletedTask;
});
But this is not what i want, i want to stay inside the servicestack request.
update 2
Looking at the source-code i find HttpHandlerFactory has a property NotFoundHttpHandler Which is filled from the AppHost.
CustomErrorHttpHandlers.Add(HttpStatusCode.NotFound, new PageNotFoundHandler());
The only downside is that i can't provide any request specific information to this Urlhandler, such as the url itself:
public class PageNotFoundHandler : RestHandler
{
public PageNotFoundHandler()
{
var restPath = new RestPath(typeof(Error404), "/Url/For?");
}
}
Trying to make this work but i'm getting stuck on that my RestHandler has different amount of components than the url since this PageNotFoundHandler is made before the RestHandler.
But Basically what im looking for is to Handle a different service/InputDto
I've tried RequestConverters but this code is not reached when CatchAllHandlers doesn't return an Handler. so im stuck in this space in the middle. Anyway i could make all the left over routes, route to a single Dto?
.NET Core's new pipeline programming model expects you to call the next middleware if it wasn't already handled by any of the previously registered middleware which is how .NET Core lets you combine multiple different middlewares into the same App.
Handling Not Found Requests with the last Middleware
The last middleware that's registered will be able to handle any unhandled requests so for instance if you wanted to return a static image for unhandled requests you could register middleware after ServiceStack, e.g:
app.UseServiceStack(new AppHost());
app.Use(new StaticFileHandler("wwwroot/img/404.png"));
Or if you wanted to return a custom 404 page instead:
app.Use(new RazorHandler("/404"));
Which will render the /wwwroot/404.cshtml Razor View with ServiceStack's MVC Razor Views.
This would be the preferred way to handle Not Found requests in .NET Core in which you will be able to register additional middleware after ServiceStack to handle non-ServiceStack requests.
Calling a ServiceStack Service for unhandled requests
If you wanted to call a ServiceStack Service for any unhandled requests you can use a Fallback Route which matches on any request, e.g:
[FallbackRoute("/{Path*}")]
public class Error404
{
public string Path { get; set; }
}
public class UnhandledRequestService : Service
{
public object Any(Error404 request) => ...;
}

ServiceStack NativeTypesFeature AddResponseStatus

I'm writing a backend using ServiceStack. our main front end client is an Angular 2 application using TypeScript. To that end, we are using the DTOs that are generated by the services when hitting /types/typescript and /types/typescript.d. This all works fine and good using the JsonServiceClient... but it seems that the response status code is somehow wrapped up in the call and not returned as it as when using a standard XHR call.
Finding the AddResponseStatus configuration item, I changed the service configuration to add this on any DTO that didn't already have the property (which mine didn't):
var ntf = new NativeTypesFeature();
ntf.MetadataTypesConfig.AddResponseStatus = true;
Plugins.Add(ntf);
After refreshing the TypeScript reference, I can see that all DTO types returned now have a ResponseStatus property on them.
export class QueryReportResponse
{
Data: string;
ResponseStatus: string;
}
Here is a scrubbed return (removed the 'Data' portion) showing the property exists on the object:
<QueryReportResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/blah.blah.ServiceModel.Messages">
<Data>
blah blah data here
</Data>
<ResponseStatus i:nil="true"/>
</QueryReportResponse>
Now, I assumed (wrongly so) that by doing this, some sort of status would be set 'automatically'. I'm obviously not right here, as this property is not set. My front end guy is asking to be able to see the status on all returned calls, like he was able to before when using straight XHR prior to using the JsonServiceClient, as now he cannot see the return status.
What is the intent of this field? I cannot set it manually, as it's added by ServiceStack dynamically at runtime. I can only assume that I would have to create my own base class return DTO of sorts and set that on the way back to the caller... can someone help me understand the purpose of this field? Thanks.
ServiceStack's Add TypeScript Reference is typically used with the TypeScript servicestack-client. The ResponseStatus is used in ServiceStack's Error Handling which is used to capture structured Error Information. It's not populated for successful responses and it's distinct from the HTTP Response Status code although if throwing a HTTP Error the ResponseStatus.ErrorCode will typically contain the HttpStatusCode enum string.
Adding ResponseStatus on DTOs
Adding the ResponseStatus on DTOs, e.g:
ntf.MetadataTypesConfig.AddResponseStatus = true;
Just adds the ResponseStatus on generated DTOs where they didn't previously exist. It doesn't have any effect on Response DTOs which already includes the ResponseStatus property, e.g:
public class MyResponse
{
public ResponseStatus ResponseStatus { get; set; }
}
Accessing HTTP Status Responses
Developers shouldn't care what the HTTP Status code is for successful responses (which is almost always 200 OK). ServiceStack's TypeScript JsonServiceClient will just return the Typed Response DTO for successful responses, e.g:
var response = await client.post(request)
They should only be interested for handling error responses, however it's expected to use the ResponseStatus.ErrorCode to determine the type of Error and apply application error handling logic, e.g:
try {
var response = await client.post(request)
} catch (e) {
console.log(e.responseStatus.errorCode);
}
If they really want the HTTP Status they can get it using a response filter, e.g:
var status = null;
try {
client.responseFilter = res => status = res.status;
var response = await client.post(request)
} catch (e) {
console.log(status, e.responseStatus.errorCode);
}

alert in SSJS Library

I have a function in SSJS Library. I would like get Client Side alert in Library. What i tried was not worked. I think I miss something. :(
function docAlive()
{
try
{
var otherDoc:NotesDocument= null;
if (funcDoc.getItemValueString("DocUNID")!="")
{
var otherDoc:NotesDocument = dbKontak.getDocumentByUNID(funcDoc.getItemValueString("DocUNID"))
if (otherDoc==null)
{
hataKod = "10001";
hataMsg = "There is no document :( Created One";
print (hataKod +": "+hataMsg);
view.postScript("alert('"+hataKod + " - " +hataMsg+"');");
}
}
return otherDoc;
}
catch (e)
{
e.toString();
}
}
view.postScript() will trigger a client-side alert, but as Tim Tripcony mentions, not in all events. And the alert will only be triggered after the function and any other code for the partial refresh has completed. At that point the HTML to trigger the (Client-Side) JavaScript alert will be posted back to the browser and the browser will action it.
If you want to throw an error back to the browser, I would strongly recommend XPages OpenLog Logger (and not just because I contribute and support it on OpenNTF). openLogBean.addError(e) will log the error to OpenLog and post an error message back to the browser.
The message is passed to the server using facesMessage.addMessage(), as documented here http://www.intec.co.uk/returning-error-messages-from-ssjs-through-the-facescontext/. I believe there are additional options for managing different message levels (e.g. WARNING, CONFIRMATION). FacesMessage is a standard Java (in this case, JSF) construct, so the documentation for it on the web is valid for XPages as well.

Server Cannot Append Header After HTTP headers have been sent Exception at #Html.AntiForgery

I'm developing an asp.net mvc 5 application in which I was trying to redirect to the ReturnUrl by applying the code below :
[HttpPost]
[AllowAnonymous]
public ActionResult Login(UserLogin model, string returnUrl)
{
if (ModelState.IsValid)
{
string EncryptedPassword = GetMD5(model.Password);
if (DataAccess.DAL.UserIsValid(model.Username, EncryptedPassword))
{
FormsAuthentication.SetAuthCookie(model.Username, true);
if (String.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index", "Home");
}
else
{
Response.Redirect(returnUrl);
}
}
else
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View();
}
The above code is working fine, But the problem is that when I Post the login form, it gives me an Exception that I've never faced Before and I'm having difficulties resolving the exception that is generating in the view in Login.cshtml, At Line :
#Html.AntiForgeryToken()
And the Exception That it throws:
Server cannot append header after HTTP headers have been sent.
I've researched a lot but I'm unable to get to the conclusion. My application works fine when I remove #Html.AntiForgeryToken() line, But I don't want to do this, I want my application to remain cross-site request protected.
Can Anyone Please Help me out, How do I get rid of this Exception?
When Response.Redirect(anyUrl) the status code is set to 302, and the header will added to the response :
HTTP 1.0 302 Object Moved
Location: http://anyurl.com
And when ViewResult is executed and razor render the view the Html.AntiForgeryToken() will called, so the helper tries to add the header X-Frame-Options and some cookies to the response, it is the cause of the exception.
But don't worry you can suppress the addition of X-Frame-Options header, just put this AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in the Application_start.
But I suggest you to change this:
Response.Redirect(returnUrl);
to
return Redirect(returnUrl);
Note
Since .NET code was opened you can see how the AntiForgeryToken works, see here AntiForgeryWorker.
I was getting same error with Response.Redirect(returnUrl). After changing to Response.Redirect(returnUrl, false) fixed the issue.

Play Framework 2.x always send single response code

Hopefully you guys can help me with this! I have a problem where I need to send a constant response code no matter what the request contains. If the request has bad JSON etc. The response I need to send is a 204 (No Content)
Here's my code where I try to send back a no content header.
public Result response(){
RequestBody body = request().body();
System.out.println(body.asJson());
return noContent();
}
Now if I try and send a request containing JSON like below. It returns a 400 (Bad request). I want to send a 204 no matter what. Please let me know what you guys come up with.
JSON POST
{
"mike":"mike
}
Thanks
Edit:
Sorry I replaced one of these lines of code and forgot to update this. Above I only return 204's, but if my client sends me bad JSON then I still return a 400.
You need to modify the global settings for play.
Create a class that extends Global Settings and override whichever method you want.
public class Global extends GlobalSettings {
#Override
public Promise<Result> onBadRequest(RequestHeader arg0, String arg1) {
super.onBadRequest(arg0, arg1);
return F.Promise.promise(()->{return play.mvc.Results.noContent();});
}
}
For more information : https://www.playframework.com/documentation/2.4.x/JavaGlobal
To return 204, you can use noContent method
For that replace ok() by noContent()
Try this,
#BodyParser.Of(BodyParser.Json.class)
public static Result response() {
JsonNode json = request().body().asJson();
if(json == null){
return noContent();
}else{
// Get json content from request and process rest..
}
return ok("");
}
By using above approach, a 204 HTTP response will be automatically returned for non JSON requests.

Resources