Custom exception with properties

After some research, I found that a custom exception should look like this:

using System;
using System.Runtime.Serialization;

namespace YourNamespaceHere
{
    [Serializable()]
    public class YourCustomException : Exception, ISerializable
    {
        public YourCustomException() : base() { }
        public YourCustomException(string message) : base(message) { }
        public YourCustomException(string message, System.Exception inner) : base(message, inner) { }
        public YourCustomException(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}

But I have a little problem.

I want the exception above two additional fields, for example int IDand int ErrorCode. How to add these two fields and initialize them - should I add a new constructor with these two parameters and the message parameter?

Also can you help me and show how to write serialization methods for this new class that will have two new properties?

Thanks.

+4
source share
1 answer

. .NET-?

 [Serializable()]
        public class YourCustomException : Exception, ISerializable
        {
            public Int Id { get; set; }
            public Int ErrorCode { get; set; }
            public YourCustomException() : base() { }
            public YourCustomException(string message) : base(message) { }
            public YourCustomException(string message, System.Exception inner) : base(message, inner) { }
            public YourCustomException(SerializationInfo info, StreamingContext context) : base(info, context) { }
            public YourCustomException(string message, int Id, int ErrorCode)
                : base(message)
            {
                this.Id = Id;
                this.ErrorCode = ErrorCode;
            }
        }
+4

Source: https://habr.com/ru/post/1610885/


All Articles