Link between layers in an application

Suppose we have the following method at the business level. What is the best practice to tell the user interface layer that something went wrong and also give an error message? Should the method return an empty string when it was okay, otherwise it is an error message, or should it throw another exception in the catch code that wraps the exception caught? If we choose the second option, then the user interface should have another attempt, to catch that to try too much, to catch, maybe. Here is the pseudo code for the first option.

public String updateSomething()
{
   try
   {
      //Begin transaction here
      dataLayer.do1();
      dataLayer.do2();
      dataLayer.doN();
      //Commit transaction code here
   }
   catch(Exception exc)
   {
      //Rollback transaction code here
      return exc.message;
   }

   return "";
 }

Is this good practice or do I need to make another exception in catch (then the method will be invalid)?

+3
4

String ( ). :

  • , - " ", , , ;

  • void, ( )

, . , "". , , / /, , .

+1

-.

:

public class ServiceOperationResult<T>
{

    public bool Successful
    {
        get; 
        set;
    }

    public ServiceErrorType ErrorType
    {
        get;
        set;
    }

    public string ErrorMessage
    {
        get;
        set;
    }

    public T ReturnData
    {
        get;
        set;
    }
}

generics, , , , ( -, " ", " ", " -" ), .

, - , ( -) ( Windows).

- ( ) - " ". , , .

+5

- . updateSomething() , - (: UpdateFailedException), catch .

public String updateSomething() {
  try {
    [...]
  } catch ( SQLException e ) {
    // rollback;
    throw new UpdateFailedException(e);
  }
}

- . , . : SQLException, DataAccessException (Spring DAO) ..

Exception, InterruptedException NullPointerException. .

+2

, , , , , , .

  • .
  • , .

for example, you encounter an exception at the business level and want to report the presentation level

public string DummyFunction
{
   try
   {

   }
   catch(Exception ex)
   {
      throw new businessException();
   }
}
0
source

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


All Articles