如何在不同的返回类型函数中返回错误信息? [英] How do i return error message in different return type function?
本文介绍了如何在不同的返回类型函数中返回错误信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此功能连接到postgres数据库并返回数据集。
This function connects to postgres database and returns Dataset.
我想要的两件事情
- 如果我收到错误我该如何返回?
-
这是返回数据集的最佳方式吗?
- If i get an error how can i return it ?
Is this the best way to return Dataset ?
string strODBCDriverName = "DSN=Postgres_32";
public DataSet SelectDataSet(string sql, bool isProcedure, Dictionary<string, object> parameters = null) {
using (OdbcConnection odbcConnection = new OdbcConnection(strODBCDriverName))
{
odbcConnection.Open();
using (OdbcCommand odbcCommand = new OdbcCommand(sql, odbcConnection))
{
if (isProcedure) odbcCommand.CommandType = CommandType.StoredProcedure;
else odbcCommand.CommandType = CommandType.Text;
if (parameters != null)
foreach (KeyValuePair<string, object> parameter in parameters)
odbcCommand.Parameters.AddWithValue(parameter.Key, parameter.Value);
using (OdbcDataAdapter adapter = new OdbcDataAdapter(odbcCommand))
{
using (DataSet ds = new DataSet())
{
try
{
adapter.Fill(ds); return ds;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
}
}
}
}
}
}
推荐答案
我喜欢通用结果
class
可以重复使用:
I like having generic Result
class
that can be reused:
internal class Result
{
internal bool IsFailure => !IsSuccess;
internal bool IsSuccess { get; }
internal string Error { get; }
protected Result(bool isSuccess, string error) {
IsSuccess = isSuccess;
Error = error;
}
private Result(bool isSuccess) : this(isSuccess, null) { }
internal static Result Fail(string error) => new Result(false, error);
internal static Result<T> Fail<T>(string error) =>
new Result<T>(default(T), false, error);
internal static Result Ok() => new Result(true);
internal static Result<T> Ok<T>(T value) => new Result<T>(value, true);
}
internal sealed class Result<T> : Result
{
internal T Value { get; }
internal Result(T value, bool isSuccess) : this(value, isSuccess, null) { }
internal Result(T value, bool isSuccess, string error) : base(isSuccess, error) {
Value = value;
}
不仅可以使用 DataSet
,但是任何类型。
This can be used not only DataSet
, but any type.
在你的情况下,返回将是 Result< DataSet>
并返回成为:
In your case return would be Result<DataSet>
and returns can become:
返回ds
- > new Result.Ok(d) code>
returns ds
--> new Result.Ok(d)
throw ex
- > new Result.Fail< DataSet> ;(ex.Message)
这篇关于如何在不同的返回类型函数中返回错误信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文