How should business errors be handled in a web application?

Say that I have a web application that can store Faces in a database. Each person must have a unique email address (or username or something else). If a user tries to add a Person with an existing email address, the form should be returned with an error message (for example, with a typical verification failure).

How does such a typical error most often bubble from the service level to the controller, and then to the presentation? Should a service method throw an exception for a controller to catch or return a value or some kind of result object?

If you ultimately want to use your service level to create a web service, will that change, how can I continue?

Any suggestions or links to best practices / sample applications would be appreciated.

+3
source share
6 answers

Basically, there are two ways to do this: exceptions and returning the results of checking business rules. Each method has its advantages and disadvantages, but mainly:

Exceptions:

  • you can return only one failed result at a time Exceptions
  • easy to implement and do not complicate your business logic - just check the condition and throw a business exception
  • Exceptions only work for blocking rules.
  • open transactions can be easily rolled back

Validation of business rules:

  • you can check a few business rules and return a list of broken ones to users
  • ,
  • , .

, , , . -, .

+3

- addPerson, . :

class AddPersonResponse {
    private Person person;
    private AddPersonStatus status;
    private AddPersonFailureReason failureReason;
}

enum AddPersonStatus {
    SUCCESS, FAILURE
}

enum AddPersonFailureReason {
    DUPLICATE_EMAIL_ADDRESS,
    DUPLICATE_USER_NAME
}

, , , , .

+1

, . , Exception. , "" , "innerException". , , .

+1

, . , - , API , API . . , - .

-, , . Django, RoR, JBoss Seam .. . , , . (, NoSuchObject) (404 Not Found), . , , , . Django - , Seam - , .

- , , YAGNI DRY, .

Layering , , , , , .

+1

, " ".

Save() ( ). ControllerBase ( ) , .

ControllerBase MVC AddModelError. , "isValid" JSON.

+1

, Spring MVC, - Validator. , , . , Errors . Person , , .

0

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


All Articles