Adding extra data to HttpResponseMessage/Exception (throwing an exception with multiple arguments) - vb.net

I have an errorbox in my web application that appears whenever a certain type of exception is caught. At the moment the exception is thrown with a string, that I can then insert into my errorbox. I would now like to also give it e.g. a color, so that I (in case of an exception) can set both the color and the text of the errorbox.
Once I catch an exception I throw a new HttpResponseException with a ReasonPhrase and a StatusCode. These are both used whenever I handle the exception. I actually use a custom exception type that currently only has a message called MyException in this example.
It looks like this:
Public Class MyException
Inherits Exception
Public Sub New(message As String)
MyBase.New(message)
End Sub
End Class
I've heard about using some sort of Data or Content property for the HttpResponseMessage, but I don't quite understand how I would use that.
Here's the vb.net code for the catching of an exception:
Catch myEx As MyException
Dim resp = New HttpResponseMessage(HttpStatusCode.ExpectationFailed) With
{
.ReasonPhrase = myEx.Message,
.StatusCode = HttpStatusCode.ExpectationFailed
}
Throw New HttpResponseException(resp)
When I throw the exception to start with, I would want to do something like:
Throw New MyException("Some error text", 5, "yellow", true)
For instance.
And then insert those extra arguments into the HttpResponseMessage somehow.
Any help would be greatly appreciated :)

Related

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";
}
}

How to dig into Exception data in VB.NET

I'm finding it hard to find the answer to my query in existing answers of Stackoverflow that's why I've decided to ask the question.
I want to handle the error with Try Catch but the default information from e.Message is not what I need.
Basically when using a breakpoint I can see that the Exception object has the data available when I dig in.
The PositionMessage type is string so I want to use this data to feed into Catch behavior. I just can't figure out how to assign the value from this specific field into a variable.
I hope you can help me with this.
The exception may be of type System.Management.Automation.RuntimeException in which case it implements IContainsErrorRecord. This means it has an ErrorRecord property (what you're looking for). You can try to cast it, and if it succeeds, you can access PositionMessage. Else (it's not a RuntimeException), then just treat it as a normal Exception.
Sub Main()
Try
' do stuff
Catch ex As Exception
Dim e = TryCast(ex, IContainsErrorRecord)
Dim message As String
If e IsNot Nothing Then
message = e.ErrorRecord.InvocationInfo.PositionM‌​essage
Else
message = ex.Message
End If
Console.WriteLine(message)
End Try
End Sub
NB: This is C#, but trivial to convert to VB. I do something like this:
results = pipeline.Invoke();
if (pipeline.Error.Count > 0)
{
var errors = pipeline.Error.Read() as Collection<ErrorRecord>;
if (errors != null)
{
foreach (ErrorRecord err in errors)
{
Console.WriteLine(err.InvocationMessage.PositionMessage);
}
}
}

Extract the user-defined Error message from exception

Inside my stored procedure, i just checked a particular condition and i'll throw Exception if that condition fails. like below,
Raise Exception '%', 'Hello world';
It is working fine, But the error message Hello world also comes with some other error code like stuffs like below in my front end,
DA00014:ERROR: P0001: Hello world
|___________________|
|
I really dont want this part to get displayed in the front end.
Is there any proper way available to filter out/Extract the right message from thrown exception.?
[Note: Please don't suggest me to do some string manipulations.]
DBMS : POSTGRESQL 9.0.3
Driver : Npgsql 1.0
Front End : VB.net
Npgsql Fastpath
If NpgsqlException.Errors is null in your exception handler then you have most likely hit a bug in Npgsql Fastpath (well I consider it a bug anyway). Here is the offending line in version 2 but the same issue exists in version 1.
It basically boils down to this code where a proper NpgsqlError is constructed and then thrown away when raising the exception by calling ToString() on it.
NpgsqlError e = new NpgsqlError(conn.BackendProtocolVersion, stream);
throw new NpgsqlException(e.ToString());
The fix would be as simple as changing the code to this and using the already supported ability of NpgsqlException to take in a list of NpgsqlError in the constructor.
NpgsqlError e = new NpgsqlError(conn.BackendProtocolVersion, stream);
throw new NpgsqlException(new ArrayList(e));
So in summary you can't do it without string manipulation unless you compile your own version of Npgsql patching the issue.
Npgsql
If you aren't using Fastpath then the thrown NpgsqlException object contains an Errors property which should be a non null list. This is an example of extracting the message from the first error.
(ex.Errors[0] as NpgsqlError).Message
try this..
Inside your store procedure place an extra character in message. e.g
Raise Exception '%', '|Hello world';
On Front end split your message on character "|", and display second index of array. e.g
Try
' your code..
Catch ex As Exception
Dim arr As String() = ex.Message.Split("|")
If arr.Count > 1 Then
MessageBox.Show(Convert.ToString(arr(1)))
Else
MessageBox.Show(Convert.ToString(ex.Message))
End If
End Try
If i understood, you can try this once
IF condition match -- (your condition)
BEGIN
RAISERROR('Hello world', 16,16)
return
END
and in expception
can use like
catch(exception ex)
{
// ex.Message
// ex.InnerException.Message
}
This should work:
Catch ex As Exception
lblMsg.Text = ex.Message.Replace("ERROR: P0001: ", "")
End Try

InvalidOperationException is ignored in try/catch block

I have the following coding
try
{
var foundCanProperty = properties
.First(x => x.Name == "Can" + method.Name);
var foundOnExecuteMethod = methods
.First(x => x.Name == "On" + method.Name);
var command = new Command(this, foundOnExecuteMethod, foundCanProperty);
TrySetCommand(foundControl as Control, command);
}
catch (InvalidOperationException ex)
{
throw new FatalException("Please check if you have provided all 'On' and 'Can' methods/properties for the view" + View.GetType().FullName, ex);
}
I'd expected that if the methods.First() (in second var statement) throws an InvalidOperationException, I'd be able to catch it. But this seems not be the case (catch block is ignored and the application terminates with the raised exception). If I throw myself an exception of the same type within the try block, it gets caught. Does Linq use multihreading so that the exception is thrown in another thread? Perhaps I make also a stupid error here and just do not see it :(.
Thanks for any help!
I know that this isn't an answer, but rather some additional steps for debugging, but does it change anything if you instead try to catch the general type "Exception" instead of the IOE? That may help to isolate if the method is truly throwing an IOE, or if its failure is generating an IOE somewhere else in the stack. Also - assuming this method isn't in main() - is there a way to wrap the call to it in a try/catch and then inspect the behavior at that point in the call flow?
Apologies, too, in that I know very little about the SilverLight development environment so hopefully the suggestions aren't far fetched.
InvalidOperationException exception occures when The source sequence is empty.
refere to http://msdn.microsoft.com/en-us/library/bb291976.aspx
check weather "properties" or "methods" is not empty.
out of interest, Why you not using FirstOrDefault ?

Retrieving parameter values using Microsoft Enterprise Library Exception Handler

We are using Enterprise Library for all our logging and exception handling needs in our app. We have added an email listener to send all the caught exceptions in email to the administrator. One requirement is that when an exception occurs in a method we need to retrieve the parameter values of the method if any and attach it to the exception details in the email sent. Is it possible without writing a custom logger?
Just create a custom exception, setting the message to the parameters:
try {
...
} catch(Exception ex) {
var customException = new CustomException(ex, string.format("Param1 {0}, Param2 {1}", param1, param2));
bool rethrow = ExceptionPolicy.HandleException(customException, PolicyName);
}
verified that in fact the ExceptionFormatter class will indeed traverse all inner exceptions, so your CustomException could be as simple as
public class CustomException : Exception
{
public CustomException(string message, Exception innerException) : base(message, innerException)
{
}
}