Sentry logging with multiple extra parameters - sentry

I have a question regarding how to include extra information in a sentry log. I have the below method to write an error log with error message and stack trace. Is there a way to add additional parameters (eg: Data), rather just being able to select one? Thanks
public void LogError(Exception exception)
{
_ravenClient.CaptureMessage(exception.Message, ErrorLevel.Fatal, extra:exception.StackTrace);
}

Related

Dynamics 365 on premises- Wep Api - Error Response

The Web API on error response includes stack trace and inner exception. Due to security reasons, we want to remove stack trace from error response.
May I know how to do these configurations?
This is existing sample error response:
{
"error":{
"code":"","message":"Resource not found for the segment '***_experienceses'.",
"innererror":{
"message":"Resource not found for the segment '***_experienceses'.",
"type":"Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException",
"stacktrace":"at Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.ParsePath(ICollection`1 segments)\r\n at Microsoft.OData.Core.UriParser.Parsers.ODataPathFactory.BindPath(ICollection`1 segments, ODataUriParserConfiguration configuration)\r\n at Microsoft.OData.Core.UriParser.ODataUriParser.Initialize()\r\n at System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath, ODataUriResolverSetttings resolverSettings, Boolean enableUriTemplateParsing)\r\n at System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataPathHandler.Parse(IEdmModel model, String serviceRoot, String odataPath)"
}
}
}
We want to be like that:
{
"error":{
"code":"","message":"Resource not found for the segment '***_experienceses'."
}
}
Stop CRM async service. Then start again and published all.
I believe that this is NOT possible from within Dynamics 365. The web API documentation has no mention of being able to customize the content of error messages. They will always be delivered in the same format.
Microsoft Docs: Parse errors from the response
If you are really concerned about the stack trace being exposed you could created a custom web API that sits between D365 and whatever is consuming the D365 data. This wrapper API could strip out the data you are concerned about.
It's dirty but I don't think you have any other options...

Catching exceptions when using <int-xml:validating-filter>

I am pulling data from queue and then validating the input payload using int-xml:validating-filter. I have set throw-exception-on-rejection="true" so that exception is thrown.
I need to get hold of the exception message(validation errors) as well as the input payload. Could you please suggest the options available to capture this data?
<int-jms:message-driven-channel-adapter id="jmsIn"
destination="requestQueue" channel="orderChannel"/>
<int-xml:validating-filter id="validatingFilter"
input-channel="orderChannel"
output-channel="validOutputChannel"
discard-channel="errOutputChannel"
schema-type="xml-schema"
throw-exception-on-rejection="true"
schema-location="OrderProcessing/order.xsd"/>
You concern isn't clear, if you can catch that exception.
The code in the XmlValidatingMessageSelector looks like:
if (this.throwExceptionOnRejection) {
throw new MessageRejectedException(message, "Message was rejected due to XML Validation errors",
new AggregatedXmlMessageValidationException(
Arrays.<Throwable>asList(validationExceptions)));
}
So, that MessageRejectedException has the desired message as a cause for validation failure. And all the validation errors are represent in the AggregatedXmlMessageValidationException cause of that MessageRejectedException.

Application.Current.Properties - System.AggregateException

I'm trying to get some data from Application.Current.Properties storage. Unfortunately, any time I want to use this Dictionary, I see this error:
An exception of type 'System.AggregateException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: One or more errors occurred.
And in details I found this:
{"Error in line 1 position 206. Element 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value' contains data of the 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfstring' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'ArrayOfstring' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer."}
It seems like I tried to save some non-string data to Application.Current.Properties. Unfortunately I can't run .Clear() method to erease all data, bacause I receive this error any time I'm trying to access this property.
What should I do to make it work?
Well, as its name suggests AggregateException, is just a container for one or more exceptions which may be thrown when using PLINQ or TPL.
As such exceptions may be thrown on different threads and may also occur concurrently, the system automatically catches and rethrows them within an AggregateException wrapper to ensure that they all get reported in one place. The exceptions themselves are exposed via the InnerExceptions property.
You can catch an AggregateException and check which exceptions it actually contains with code such as the following:
try
{
// perform some parallel operation
}
catch (AggregateException aex)
{
string messages = "";
foreach(Exception ex in aex.InnerExceptions)
{
messages += ex.Message + "\r\n";
}
MessageBox.Show(messages);
}
So I suggest you do this to see what is causing the problem
Please, remove your app from your device, Settings - Applications- Uninstall, this works for me. The Auth Object was crash in debug mode.Clean and Rebuild can be Helpfull to.

log4net on WebApi 2.1 using ExceptionLogger

How does one properly implement WebApi 2.1's ExceptionLogger so that log4net logs the correct values for method, location and line?
What I'm trying to achieve is a global exception logger to log all unhandled exceptions in a WebAPI 2.1 v5.1.2 app running .NET 4.5.1. I've read quite a few articles including the one linked below explaining how to implement the ExceptionLogger, and it works great, except that I can't get log4net to output the values I really want to record.
For example, if I log an exception from a controller, everything is correct. When I log from the ExceptionLogger, I'm getting the values from the Logger itself, and not the method that initiated the exception. I tried a few things listed in my code below, but they're not quite right. Here's what I get.
I know the text is small, but the table shows the different values log4net writes. The first log is from the controller, everything is great. The 2nd entry is from log.Logger.Log in the code snippet. The last entry is from log.Error in the snippet.
The final method in the snippet attempts to use a limiting type as I've read from other implementations of log4net wrappers, but it just throws an error, as described in the snippet.
So, HOW CAN I GET THE VALUES LIKE THE ONES I WOULD RECEIVE IF CALLING FROM A CONTROLLER, WHEN USING A GLOBAL ExceptionLogger ?
public class GlobalExceptionLogger: ExceptionLogger
{
//private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void Log(ExceptionLoggerContext context)
{
StackTrace stackTrace = new StackTrace(context.Exception);
Type methodDeclaringType = stackTrace.GetFrame(2).GetMethod().DeclaringType;
ILog log = LogManager.GetLogger(methodDeclaringType);
string message = context.ExceptionContext.Exception.Message;
//this methods works but writes the location, method name and line from this method, not the caller
//location: System.Web.Http.ExceptionHandling.ExceptionLogger.LogAsync(:0)
//method: LogAsync
//line: 0
log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, log4net.Core.Level.Error, message, context.ExceptionContext.Exception);
//this methods works but writes the location, method name and line from this method, not the caller
//location: Company.AppName.Api.GlobalExceptionLogger.Log(c:\TFS\AppName\AppName.Api\GlobalExceptionLogger.cs:38)
//method: Log
//line: 38
log.Error(message, context.ExceptionContext.Exception);
//this method throws an error in the log4net debug: log4net:ERROR loggingEvent.LocationInformation.StackFrames was null or empty.
log.Logger.Log(methodDeclaringType, log4net.Core.Level.Error, message, context.ExceptionContext.Exception);
}
}
http://weblogs.asp.net/jongalloway//looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-4-web-api-help-pages-bson-and-global-error-handling
Your method of getting the stacktrace is not recommended, because the code will behave differently on debug/release or precessor architecture. The method stackTrace.GetFrame(2).GetMethod() will give you the method on the real stack, with taking into consideration the optimalizations of the runtime for processor architecture, linq rewrites etc.
An alternative method of getting the member name:
public static string LogError(Exception ex, [CallerMemberName] string callerName = "")
You should have a look at this question:
stackframe-behaving-differently-in-release-mode

Is it a good or bad idea throwing Exceptions when validating data?

When validating data, I've gotten into a habit of doing the following:
Note: I don't really have individual booleans for each check. This is just for the example.
Another Note: any error handling during the tests are done properly. The ONLY exceptions thrown in the try-catch are my own.
try {
if (validCheckOne = false) {
throw new Exception("Check one is bad");
}
if (validCheckTwo = false) {
throw new Exception("Failed because of check2");
}
if(validCheckTen = false) {
throw new Exception("Yet another failure on your part: check10.");
}
} catch(Exception e) {
MessageBox.Show("Your stupid data is wrong! See for yourself: " + e.Message);
}
Is this bad practice? Does throwing Exceptions slow the program's execution or is inadvisable?
Personally I like throwing Exceptions for business rule validation (not so much for user input validation) because it forces the problem to be handled upstream. If my business objects returned some kind of validation result, it could be ignored by the caller. Call me a cowboy if you wish :)
Everyone here is repeating the phrase "exceptions are for exceptional circumstances", but that really doesn't give any understanding of why its bad to use them for unexceptional circumstances. I need more than that. Is the performance hit of throwing exceptions really that bad? Are there any benchmarks available?
I'm going to repeat the mantra here: throwing exceptions should be done in exceptional circumstances. Invalid entered data is really not that exceptional.
I support MusiGenesis's answer.
Additionally...
The performance of throwing an exception is a thousand instructions. It's nothing compared to end-user time, but in inner code it is slow.
An additional problem is that, using Exceptions, your validation is limited to reporting the first failure (and you will have to do it all again next time to find the next failure).
In addition to the oft-repeated statement that "exceptions are for exceptional circumstances", here's an additionally clarifying rule I've come to like:
If the user caused it, it's not exceptional.
Exceptions are for system-side things (servers going down, resources being unavailable), not for the user doing odd things, because all users do odd things.
It depends - if you are expecting the data to be there and NOT having the data is unexpected, then throwing an exception is OK. Throwing an exception is very expensive (slow) but is the best way to handle unexpected circumstances.
In the title you call it "validating" data. That can happen on several levels. In (near) the GUI where you are checking user entered data, you should be expecting errors and have ways to report the errors back. Exceptions are inappropriate in this case.
But Data Validation can also happen at other boundaries, say between business-rule classes. There, errors in the data are uncommon and unexpected. You should throw when you detect one.
So maybe in some languages exception throwing and catching is "costly" but in other languages, throwing and catching exceptions is exactly what's called for.
In Smalltalk, for example, one could quickly build a multi-tiered exception catching solution. The validation pass could collect up any number of exceptions representing EVERYTHING that's wrong with a particular input data set. Then it would throw them ALL up to a higher-level catcher, responsible for formatting up a human-readable explanation of, again, EVERYTHING that was wrong with the input. In turn it would throw a single exception further up the chain, along with that formatted explanation.
So... I guess what I'm saying is, exceptions are only bad to throw if you've got no exception handling architecture supporting catching them and doing reasonable things with them, and all your catcher is going to do is EXIT or do something else equally inappropriate.
This is bad behavior. Exceptions are for Exceptional conditions. They take resources to generate the stack etc. Exceptions should not be used to dictate process flow.
In general it is inadvisable to use Exceptions to implement conditional flow. It would be better to do something like this
error = false;
while(true) {
if(validCheckOne == false) {
msg = "Check one is bad";
error = true;
break;
}
if(validCheckTwo == false) {
msg = "Check two is bad";
error = true;
break;
}
...
break;
}
if (error) {
..
}
You should throw an exception when there is a situation you can't do nothing about it. Higher layers of software would have a chance to catch the exception and do something about it - even if that is simply crashing the application.
I would suggest that using exceptions as described in the question (for flow control within a function) is wrong not usually the best idea. I'd go further and saying validation throwing exceptions isn't the best approach; instead return a Boolean and store a list of validation error messages that can be accessed. An accompanying save method could/should throw an exception if it is called on an invalid object.
Thus if validate fails validation error messages can be displayed to the user (logged, returned. whatever). If validation passes then you can call save.
If you call save on an invalid object then get get an appropriate exception.
Another potential problem with your example code (depending on requirements of course) is it only throws the first validation error that occurs. Imagine this from a users POV:
Click save
Get an error message
Correct error
Click save again
Get a different error message. Annoying.
As a user I'd prefer to get all validation errors returned at once so I can correct them all before trying again.
I generally agree with the "exceptions should be exceptional" rule, but I might make an exception (ha!) for Python, where it can be both efficient and considered good practice to use try ... except to control flow.
See Using Exceptions For Other Purposes, for example.
This question is still interesting, mainly because of the answers.
When it comes to exception, there is a lot of arguments involved. We can defend a point to any direction we want to, from performance to exception philosophy. And they all sounds right to me.
But sometimes we have to stick to a direction. In this case, I think it's the validation itself.
When we want to validate something we also want to know (to log, or to show the user) whats wrong when the parameter is invalid. Even thought there are layers of validation such as Business Validation mixed with User Input validations.
For instance, when dealing with user input, a lot of weird cases can happen. A pasted data from a website full of hidden char (\t \n etc), typos, and a really huge kinds of cases that a specific exception could allow further analysis or message to the uses much more precisely than a simple "false" return.
When you go to the grocery and ask the seller if he's got cheese, and the seller replies with no, would that be an unexpected or exceptional response?
What about if you do the same but the seller just looks at you and does not respond!
Another example, you are talking to your friend and ask if there is something wrong, you may get 2 responses:
They tell you that they are sad because of something.
Or they just look at you and say nothing, turn their back and walk away and you are sure that this means you're in deep trouble :)
Same way with exceptions, unexpected behavior is an exception, but an invalid but expected response should not - IMHO - throw exceptions.
I often write similar code for validation, especially in express.js, and similar request/response loop style applications. When something is invalid, I throw a ValidationError, it's caught by the top level error handler, which knows to send a 422 response with the additional information that's attached to the ValidationError.
It's a very convenient way to handle validation. You don't have to pass around an error object (potentially up through a dozen stack frames, in some cases). And it's a simple and consistent way to trigger an invalid input response. I haven't experienced any serious problems with this approach.
I've thought about the "don't use exceptions for flow control" maxim in relation to this practice, and decided the benefits outweigh any disadvantages. I would say if you understand the reasoning behind "don't use exceptions for flow control", but you determine that it's a good idea anyway in a certain case, then go ahead and do it. We don't need to be too dogmatic about these things.
Throwing exceptions is relatively slow, but that will only matter if you're doing it repeatedly in a loop.
It really only matters if your data validation is in a tight loop. For most cases, it doesn't matter what you choose as long as you are consistent in your code.
If you have a lot of code that looks like your sample above then you might want to clean it up by introducing a helper method to throw...
private void throwIf( bool condition, String message )
{
if( condition )
throw new ApplicationException( message );
}
(also, doing this will help zero in on errors such as "validCheckOne = false" versus "validCheckOne == false" :)
Well, i know it's an old question. But i'll let my opinion here for the googler's who falled here like me:
If you are using a language with a bad try/catch support AVOID
THROWING exceptions for data validation;
DO NOT THROW a exception that will not be handled by the caller or
alserwhere;
DO NOT THROW a exception if you need to validate the rest of the received data;
You can THROW a exception in cases where the code block cannot continue
without the invalid data; And if you do not interrupt the process you
can get a unhandled exception;
An example:
/*
* Here it's a common problem i have: Someone pass a list of products i need to
* retrieve from the database and update some information;
*/
//This is a class to represent the product
function Product(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
//This is an example function to retrieve the product from the database
function findProductInDatabase(productId) {
//If the product exists on the database, the function will return it
if (productId == 12) {
var product = new Product(12, "Book", 20.5);
return product;
}
//If the product do not exists, it will return null
return null;
}
//This is a function that will receive the productID and will update the received parameters
function updateProduct(productId, newProductName, newProductPrice) {
var productFromDatabase = null;
var errorMessage = "";
//Retrieve the product
productFromDatabase = findProductInDatabase(productId);
//If the product do not exist, i need to interrupt de method imediatily and alert the caller
if (!productFromDatabase) {
throw "Product not found";
}
//Validate the other parameters, but in this case i can validate all the parameters
if (newProductPrice < 10) {
errorMessage += "the price is too low";
}
if (newProductName.includes("<")) {
//If already has a error message in the variable i append " and " to the message make sense
if (errorMessage) {
errorMessage += " and ";
}
errorMessage += "the new name has invalid characters";
}
if (errorMessage) {
//if theres any error, i will throw a exception with the messages
throw errorMessage;
}
}
//This parte is where the method id called;
try {
updateProduct(9, "Book", 10.5);
} catch (exception) {
console.log("Case 1: " + exception);
}
try {
updateProduct(12, "<Book", 9);
} catch (exception) {
console.log("Case 2: " + exception);
}
In test, sure, but in a live environment, you'd hope they're never raised.
You'd hope to refactor your code to the extent that all data into your system are validated at source, and either the user, or the system that generated the input to your system, is notified of the issue.
Exceptions should occur if you've missed something and should be a fallback that is handled gracefully.
You could store anything that's causing these exceptions separately, so that they don't make it into your system without being checked over first.
You don't want, e.g. an invalid value that falls outside a range of values to skew your results.

Resources