D
D
Dmitry2016-08-02 21:47:04
ASP.NET
Dmitry, 2016-08-02 21:47:04

How to return errors from services?

Hello! Prompt, who as returns errors from Business layer? For example

public User Method(Guid id)
{
 if(id == Guid.Empty) throw new ArgumentException(" some message ");
 return findedUserById;
}

is it worth it to do so, is it worth using an exception, roughly speaking, to validate business rules? Who uses what methods, share

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Evseev, 2016-08-11
@alex1t

Another option is a special return class, a la ASP.NET MVC ActionResut.
Those. all methods return some Result class:

class Result<T> {
   public T Result {get; private set; }}
   public bool Success {get; private set; }}
   public IEnumerable<Exception> Errors { get ... }
   public string ErrorMessage {get ... } // этого можно и не делать

   private Result() {}
   public static Result<T> Success(T result) { return new Result() { Result = result, Success = true }; }
   public static Result<T> Fail(Exception ex) { return new Result() { Success = false, Errors = new List<Exception>() { ex }, ErrorMessage = ex.Message }; }
}

A
Alexey Pavlov, 2016-08-03
@lexxpavlov

An exception is an exceptional situation that should not occur in normal operation. But if the absence of an object is possible, and this is a normal situation (non-exceptional), then this is not an exception, it is better to return null.
Example one - the method should return the current user. Of course, the current user must be, if it is not - this is an exception.
The second example is looking for a comment on a post. Nobody left a single comment, and if you search for the found comment user, then the user will not be found, but this is not an exception - it is normal to return null.
But it is possible that it is better to make the code so that the call to this method would not be called.

S
stcmd04236, 2016-08-02
@stcmd04236

I create my own exception. If wcf is a service, then I create exceptions inherited from FaultException.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question