Service Layer

Overview

  • The Service Layer is usually constructed in discrete operations that have to be supported for a client. It provides the implementation for the application’s business logic, including such things as business rules, validations, and calculation logic.
  • Provides the implementation for the business logic of the application, including such things as business rules, validations, and calculation logic.
  • The Business Layer is at the same level as the Service Layer.
  • The service layer allows us to isolate the presentation layer from the business layer, in the same way the business and data access layer separates the persist data.
Service Layer

🚨 The Business Layer is the place where all the business/domain logic, i.e. rules that are particular to the problem that the application has been built to handle, lives. This might be salary calculations, data analysis modelling, or workflow such as passing a order through different stages.

Data Transfer Objects (DTO’s)

  • Is an object that carries data between processes.
  • The majority of the cost of each call is related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been transferred by the several calls.
  • DTO’s does not have any behavior except for storage, retrieval, serialization and deserialization of its own data.
  • DTO’s are simple objects that should not contain any business logic but may contain serialization and deserialization mechanisms for transferring data over the wire.

Mappers frameworks [ DTO → ← MODEL ]

  • This framework is necessary to map data of objects, for example: from Models to DTO’s and vice versa.

Error Message handling for REST API

  • Spring Boot provides us tools to handle exceptions beyond simple ‘try-catch’ blocks.

Custom Error Message

  • It’s necessary to implementing a structure for sending errors over the wire — the ApiError.
  • The APIError estructure:
    • status – the HTTP status code
    • message – the error message associated with exception
    • apiSubErrors – List of constructed error messages

@ExceptionHandler

  • The @ExceptionHandler annotation gives us a lot of flexibility in terms of handling exceptions.
  • The exception handler method takes in an exception or a list of exceptions as an argument that we want to handle in the defined method. We annotate the method with @ExceptionHandle and @ResponseStatusto define the exception we want to handle and the status code we want to return.

Example Service Layer

External Resources