处理代码中的格式异常 [英] handling format exception in code

查看:103
本文介绍了处理代码中的格式异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我传递错误的日期格式时,例如省略分钟部分然后抛出错误:



System.FormatException:字符串未被识别为有效的DateTime。



如何在代码中处理它以便客户获得不错的消息?



  public 列表<坐标> FetchCoordinates( String  FetchParam)
{
List< Coordinates> Coords = new List< Coordinates>();
坐标c;

if String .IsNullOrEmpty(FetchParam))
{
c = new 坐标()
{
错误= < span class =code-string>无输入
};
Coords.Add(c);
返回 Coords;
}

字符串 [] parts = FetchParam.Split('' ,');
sqlCom.CommandText = FetchCoordinates;
sqlCom.CommandType = CommandType.StoredProcedure;

字符串 IMEI = parts [ 0 ]。ToString();
DateTime DateTimeFrom = Convert.ToDateTime(parts [ 1 ]);
DateTime DateTimeTo = Convert.ToDateTime(parts [ 2 ]);

sqlCom.Parameters.Add( @ IMEI,SqlDbType.VarChar ).Value = IMEI;
sqlCom.Parameters.Add( @ DateTimeFrom,SqlDbType.VarChar).Value = DateTimeFrom;
sqlCom.Parameters.Add( @ DateTimeTo,SqlDbType.VarChar).Value = DateTimeTo;
SqlParameter sqlParam = new SqlParameter( @结果,SqlDbType.Int);
sqlCom.Parameters.Add(sqlParam);
sqlCom.Parameters [ @ result]。Direction = ParameterDirection.Output;

尝试
{
sqlCon.Open();
使用(SqlDataReader reader = sqlCom.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
c = < span class =code-keyword> new 坐标()
{
经度=读者[ 经度]。ToString(),
Latitude = reader [ 纬度]。ToString()
};
Coords.Add(c);

}
返回 Coords;
}
其他
{
c = 坐标()
{
错误= 找不到给定输入的数据
};
Coords.Add(c);
返回 Coords;
}

}

}

catch (例外)
{

c = new 坐标()
{
错误= 有些东西错了
};
Coords.Add(c);
返回 Coords;

}

finally
{
sqlCon.Close();
}
}





怎么样?

解决方案

< blockquote> Refer - 字符串未被识别为有效的DateTime 。 [ ^ 获得完整答案。


 sqlCom.Parameters。添加  @ DateTimeFrom,SqlDbType。 VarChar )。Value = DateTimeFrom; 
sqlCom.Parameters。添加 @ DateTimeTo,SqlDbType。 VarChar )。Value = DateTimeTo;





这些存储过程参数真的是字符串吗? (VarChar),如果是这样的话,我会考虑更改proc,因此它们是DateTime。



你可以进入各种可怕的问题,将日期表示为字符串。


When i pass wrong date format e.g. omitting minutes part then it throws error:

System.FormatException: String was not recognized as a valid DateTime.

how to handle it in code so clients gets decent message ?

public List<Coordinates> FetchCoordinates(String FetchParam) 
    {
        List<Coordinates> Coords = new List<Coordinates>();
        Coordinates c;
 
        if(String.IsNullOrEmpty(FetchParam))
        {
            c = new Coordinates()
                        {
                            Error = "No Input Provided"
                        };
                        Coords.Add(c);
                        return Coords;
        }

        String[] parts = FetchParam.Split(',');
        sqlCom.CommandText = "FetchCoordinates";
        sqlCom.CommandType = CommandType.StoredProcedure;

        String IMEI = parts[0].ToString();
        DateTime DateTimeFrom = Convert.ToDateTime(parts[1]);
        DateTime DateTimeTo = Convert.ToDateTime(parts[2]);

        sqlCom.Parameters.Add("@IMEI", SqlDbType.VarChar).Value = IMEI;
        sqlCom.Parameters.Add("@DateTimeFrom", SqlDbType.VarChar).Value = DateTimeFrom;
        sqlCom.Parameters.Add("@DateTimeTo", SqlDbType.VarChar).Value = DateTimeTo;
        SqlParameter sqlParam = new SqlParameter("@result", SqlDbType.Int);
        sqlCom.Parameters.Add(sqlParam);
        sqlCom.Parameters["@result"].Direction = ParameterDirection.Output;

        try
        {
            sqlCon.Open();
            using (SqlDataReader reader = sqlCom.ExecuteReader())
            {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            c = new Coordinates()
                            {
                                Longitude = reader["Longitude"].ToString(),
                                Latitude = reader["Latitude"].ToString()
                            };
                            Coords.Add(c);

                        }
                        return Coords;
                    }
                    else
                    {
                        c = new Coordinates()
                        {
                            Error = "No Data Found for Given Input"
                        };
                        Coords.Add(c);
                        return Coords;
                    }
                
                }
           
          }

        catch (Exception)
        {

            c = new Coordinates() 
            { 
                Error = "Something Went Wrong" 
            };
            Coords.Add(c);
            return Coords;

        }

        finally
        {
            sqlCon.Close();
        }
    }



how ?

解决方案

Refer - String was not recognized as a valid DateTime.[^] for a complete answer.


sqlCom.Parameters.Add("@DateTimeFrom", SqlDbType.VarChar).Value = DateTimeFrom;
sqlCom.Parameters.Add("@DateTimeTo", SqlDbType.VarChar).Value = DateTimeTo;



Are these stored procedure parameters really strings? (VarChar), if so I'd look at changing the proc so they are DateTime instead.

You can get into all sorts of horrid problems representing dates as strings.


这篇关于处理代码中的格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆