Can anyone point out why I get an exception when the .results point in the code is executed?
-- note the code has been edited after the quested was answered as per Tatham Oddie's comment. ---
public User Create(User user)
{
try
{
// Check if user exists
if (this.Exists(user.EmailAddress))
{
throw new Exception("User already exists");
}
else
{
var q = this._context.Client().Cypher
.Create("(n:User {f}")
.WithParam("f", "Mike")
.Return(n => n.As<User>());
return q.Results.Single();
}
}
catch (Exception e)
{
throw e;
}
}
Please do not write code like this: "(n:User {FirstName: '" + user.FirstName + "'}". It is a major security risk in your application, and a performance constraint.
Follow the example at https://github.com/Readify/Neo4jClient/wiki/cypher-examples#create-a-user which uses a parameter syntax.
It will be secure.
It will be faster.
It will work.
Got it. Syntax error. Missing bracket.
Related
i am unable to end response in case of some condition
eg below (in Upload Action Method), if Logerror method invoked i just want to return view(browser) without further action. i.e return from Upload Action Method.
Plase find modified question what i am trying to achive,
In case of error i want to return view by stopping all further opeartion
public ActionResult Index()
{
return View();
}
public ActionResult Upload()
{
int i=1;
DoSomethingFirst();
//if LogError i dont want execute code below, rather it should end responce
//should not reach here
string s="This should not be executed in case of LogError()";
return View("Index");
}
public void DoSomethingFirst()
{
try{
DoSomethingSecond();
}
catch(exception ex)
{
LogError();
}
}
public void DoSomethingSecond()
{
try{
DoSomethingThird();
}
catch(exception ex)
{
LogError();
}
}
public void DoSomethingThird()
{
try{
DoSomethingother();
}
catch(exception ex)
{
LogError();
}
}
private LogError()
{
Viewbag.Error="Error details";
return View("Index");
}
This doesn't return a result from the current method:
DoSomething();
But this does:
return DoSomething();
If you want to end execution of the current method, you need to do something which exits the method. Basically, either return from the method or throw an exception. Since DoSomething returns a result, presumably you want to return that result. So simply add a return statement when invoking the method.
i tried wit RedirectToAction("Index");
Same issue. You'd need to return the result:
return RedirectToAction("Index");
Edit: Based on your edit to the question, the overall concept still remains. Focusing on this part of your code here:
var s = DoSomethingFirst();
//if true i dont want execute code below, rather it should end responce
//should not reach here
In order to exit the method, any method in C#, you need to either return or throw. So the first question is... Which do you want to do here? If you want to return a redirect, for example, then return a redirect:
return RedirectToAction("SomeAction");
If you want to return the default view, return that:
return View();
If you want to throw an exception:
throw SomeException("Some Message");
The choice is yours. You just need to define:
What you want this method to return or throw under this condition.
How will you know the condition.
For that second point, your code comment says:
//if true ...
Does this mean DoSomethingFirst() returns a bool indicating success or failure? Then that would be a simple if statement:
if (!DoSomethingFirst())
return View();
Another Edit: Based on your comment below:
Inside LogError mehod called by any child method in action method, i want to update view with error message and end the operation without further operation
How will your Update method know that something it invoked internally called LogError()? What information does DoSomethingFirst() return to indicate this fact? Currently it doesn't. Your various DoSomething methods are all swallowing exceptions, which means they are internally handling exceptions so that consuming code doesn't know about them.
If you want consuming code to know about an exception, re-throw that exception. For example:
public void DoSomethingFirst()
{
try
{
DoSomethingSecond();
}
catch(exception ex)
{
LogError();
throw; // <-- this will re-throw ex without modifying it
}
}
This returns information from DoSomethingFirst(), specifically the fact that an error occurred. Your consuming code can then check for that error:
try
{
DoSomethingFirst();
}
catch (Exception ex)
{
// You should *probably* do something with ex too. So far all of your "logging" has been ignoring the actual error.
return View();
}
Regardless of the structure you build, the basics don't change. In order for consuming code to know something about the code it invokes, that invoked code has to expose that information. In order to end execution of a method, you have to either return or throw. Don't hide exceptions from consuming code if you want consuming code to respond to those exceptions.
I am trying to create standard error page for zuul server so that I can redirect exception to this page?
Currently, I have created a zuul filter to catch zuul exception as below:
code snippets
#Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
Object e = ctx.get("error.exception");
if (e != null && e instanceof ZuulException) {
ZuulException zuulException = (ZuulException)e;
LOG.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);
// Remove error code to prevent further error handling in follow up filters
ctx.remove("error.status_code");
// Populate context with new response values
ctx.setResponseBody("Internal Server Error : Please contact Phoenix Admin");
ctx.getResponse().setContentType("application/json");
ctx.setResponseStatusCode(500); //Can set any error code as excepted
}
}
catch (Exception ex) {
LOG.error("Exception filtering in custom error filter", ex);
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
appreciate for any advice?
I will have to spend some time to see how you can read from the error page I am traveling right now. But setting the response body by reading content might not be a bad option definitely might not be perfect.
Checkout the below code if it helps.
Also add some code that you might be trying and is not working its easier that way to answer and help.
You need to make sure the filter runs after the predecoration filter.
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8082").path("/outage").build()
.toUriString();
ctx.set("requestURI", url);
return null;
}
Check this out for more information:- https://github.com/spring-cloud/spring-cloud-netflix/issues/1754
Hope this helps you.
I have the following Delete Action method, which mainly perform two separate tasks:-
Delete a record from a Third party application using API call.
Delete a record from the database on our own system using entity framework.
My action method looks as follow:-
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
var message = "";
var status = "";
var tag = "";
Resource resource = new Resource();
try
{
Rack rack = repository.FindRack(id);
tag = rack.Technology.Tag;
resource = repository.GetResource(rack.Technology.IT360ID.Value);
}
catch (NullReferenceException)
{
return Json(new
{
IsSuccess = "False"
}, JsonRequestBehavior.AllowGet);
}
catch (DbUpdateException)
{
return Json(new
{
IsSuccess = "AlreadyUsed"
}, JsonRequestBehavior.AllowGet);
}
using(var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
query["username"] = "testuser";
query["assetType"] = resource.ComponentDefinition.ComponentType.COMPONENTTYPENAME;
query["operation"] = "DeleteAsset";
query["assetName"] = resource.RESOURCENAME;
var url = new UriBuilder("http://win-spdev:8400/servlets/AssetServlet");
url.Query = query.ToString();
try
{
string xml = client.DownloadString(url.ToString());
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
status = doc.SelectSingleNode("/operation/operationstatus").InnerText;
message = doc.SelectSingleNode("/operation/message").InnerText;
}
catch (WebException ex)
{}
}
if (status.ToUpper() == "SUCCESS")
{
try
{
repository.DeleteRack(id, User.Identity.Name);
repository.Save();
return Json(new
{
IsSuccess = "True", id = id, description = tag
}, JsonRequestBehavior.AllowGet);
}
catch (NullReferenceException)
{
return Json(new
{
IsSuccess = "False"
}, JsonRequestBehavior.AllowGet);
}
catch (DbUpdateException)
{
return Json(new
{
IsSuccess = "AlreadyUsed"
}, JsonRequestBehavior.AllowGet);
}
}
return RedirectToAction("Delete", new
{
id = id
});
}
As since I am using the entity framework to perform the deletion and also a API call, so I ended up with separate try/catch blocks . so does my action method logic consider a poor design since I am having multiple try/catch blocks inside the same action method? And what better approach I can follow?
Separate error cases are certainly not a bad pracice.
What is bad practice, though, is catching unspecific errors. You are returning "AlreadyUsed" for all DbUpdateExceptions. There might be other causes for this than the one you planned for. If that happens you swallow the error and have a silent bug. You might lack the imagination right now what those cases might be but that is just because you never know bugs before they happen. I advise that you catch even more specific than this by either interpreting the exception object (maybe interpret the message, god forbid) or by tightening the region that the catch covers to exactly the statement that can give the error.
In short, don't swallow exceptions indicating bugs. Bugs happen all the time, you want to know about them and fix them.
Also, for the same reason, never ever catch NullReferenceException. They are always bugs by convention. Insert an if already do deal with the null.
If the code in the try-catch is a "logical-entity", e.g. does an independent functionality that wouldnt affect the remaining code, or it wouldnt cause incorrect logic (incorrect execution) to the following code if it had an error. Then Why not.
But if it would break your program logic then it should be stopped and the error should be handled (scope of your try-catch block. it all depends on your program logic.
There is nothing wrong with limiting the try-catch scope(s) to as little as you possibly know.
(I might get flamed for this.)
Does anyone have a simple way of handling this exception when updating a record to one that already exists in the database?
Try this:
catch (UpdateException ex)
{
SqlException innerException = ex.InnerException as SqlException;
if (innerException != null && innerException.Number == ??????)
{
//Place you exception code handling here..
}
else
{
throw; //(bubble up)
}
}
This is a simple solution, but you may have issues in the future should the error number change which is unlikely).
How to catch duplicate key exceptions in Grails . when trying to save existing integer for a unique column constraint, the error is generating while saving/updating a record .
Also used
try{
object.save(flush:true)
}
catch(org.springframework.dao.DataIntegrityViolationException e){
println e.message
}
catch(org.hibernate.exception.ConstraintViolationException ex){
println e.message
}
catch(Exception e){
println e.message
}
But unable to catch this issue .
23:41:13,265 ERROR [JDBCExceptionReporter:101] Duplicate entry '1' for
key 2 23:41:13,281 ERROR [AbstractFlushingEventListener:324]
Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not
execute JDBC batch update at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
Could you please share the solution to solve this .
You're trying to save a record with an id that already exists.
If id is auto-generated, don't set it manually
If id is not auto-generated, set it to something else, for example max(id) + 1
surely no Exception should be thrown for constraint violation, but rather object.save() should return null? i.e.
if(object.save() == null) {
// save failed
} else {
// save succeeded
}
If you defined the uniqueness through a Grails constraint, you have to look for a ValidationException. This is thrown when object.validate() fails; Validation is done before any object.save().
try {
object.save(failOnError: true)
}
catch(ValidationException ve) {
// Do something ...
}
But remember: Any constraint violation, for any member variable can cause a ValidationException ... so you have to distinguish yourself.
Edit:
This applies, if you use the Grails 1.2 failOnError feature ...
I am looking for the same problem so maybe not a complete answer but what you can do is to force validation and look in the errors, identify the case and place the actions you want:
if(instance.validate()) {
//everything ok
} else {
instance.errors.each {
//identify the case and place actions
}
}
Also note that error is: className.propertyName.unique
Possibly it should work:
import org.springframework.dao.DuplicateKeyException
try {
domainInstance.save(flush: true)
} catch(DuplicateKeyException e) {
// ...
}