Hi,
If we just want to capture the server custom errors on the client-side, we could use FaultException class.
Server-side.
public string Test(string name)
{
if (name.Length<2)
{
FaultReasonText text = new FaultReasonText("name string length should greater than two ");
FaultReason fr = new FaultReason(text);
throw new FaultException(fr);
}
return DateTime.Now.ToString();
}
Client-side.
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
try
{
var result = client.Test("A");
Console.WriteLine(result);
}
catch (FaultException e)
{
Console.WriteLine(e.Reason.GetMatchingTranslation().Text);
}
We could also use the custom class. Server-side(Console application).
class Program
{
static void Main(string[] args)
{
using (ServiceHost sh = new ServiceHost(typeof(MyService)))
{
sh.Open();
Console.WriteLine("serivce is ready....");
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContract(typeof(ErrorDetail))]
void Test(string username,string password,string password2,int age);
}
public class MyService : IService
{
public void Test(string username,string password,string password2,int age)
{
ErrorDetail detail = new ErrorDetail();
if (username.Length<2)
{
detail.UserNameFaultInfo = "\nusername string length should greater than 2";
}
if (password.Length<6)
{
detail.PasswordFaultInfo = "\npassword string length should greater than 2";
}
if (password2!=password)
{
detail.PasswordFaultInfo += "\npassword is not matched";
}
if (age<0||age>120)
{
detail.AgeFaultInfo = "\nage is not valid";
}
if (detail.UserNameFaultInfo!=null||detail.PasswordFaultInfo!=null||detail.AgeFaultInfo!=null)
{
throw new FaultException<ErrorDetail>(detail, "there is something wrong with the input information");
}
}
}
[DataContract]
public class ErrorDetail
{
[DataMember]
public string UserNameFaultInfo { get; set; } = null;
[DataMember]
public string PasswordFaultInfo { get; set; } = null;
[DataMember]
public string AgeFaultInfo { get; set; } = null;
}
Feel free to let me know if there is anything I can help with.
Best Regards
Abraham
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
740 Points
321 Posts
Re: CustomError class
Aug 27, 2019 09:04 AM|Abraham Qian|LINK
Hi,
If we just want to capture the server custom errors on the client-side, we could use FaultException class.
Server-side.
Client-side.
We could also use the custom class.
Server-side(Console application).
App.config
Client(Console application) call by adding service reference.
Result.
Feel free to let me know if there is anything I can help with.
Best Regards
Abraham