Giter Site home page Giter Site logo

learningbyexample / microserviceserrorhandling Goto Github PK

View Code? Open in Web Editor NEW
2.0 3.0 1.0 67 KB

handling microservices error avoiding lost of control flow

Home Page: https://juan-medina.com/2018/02/10/microservices-errors/

License: MIT License

Shell 32.61% Batchfile 25.21% Java 42.19%
spring spring-boot microservice controlleradvice exceptions error-handling business-logic java rest rest-api

microserviceserrorhandling's Introduction

Microservices Error Handling

License: MIT Build Status codecov

info

The idea behind that project is to check how we could avoid to use ControllerAdvice and ExceptionHandler, and even checked exceptions when handling errors in our Microservices.

Checked exceptions some times could leak the implementation details of our components, and they could even break our control flow.

Spring ControllerAdvice or ExceptionHandler could become the ultimate GOTOs, that some people my use to get errors and sent back to the consumers of the Microservice, jumping out on the execution of our business logic.

The approach described in the example is to handle errors as part of our business logic, avoiding unnecessary lost of our control flow.

This example is not about stop using ControllerAdvice, we may need to still using it to handle unexpected Runtime Exceptions, however relaying on it for handling our business errors isn't ideal.

Approach like the one in this example may become a better way to do it, however this is not the unique, neither definitive, solution.

usage

We have created one wrapper class to support this concept named Result<type>, this class has two creation methods.

  • Result.create(object); : That will create a wrapper containing the data to be returned.
  • Result.error(object) : That will create a wrapper containing an error.

How to use this class is simple, for example:

public Result get(int id) {
  if (id == 1) return Result.create(new Customer(1, "super customer"));
  else if (id == -1)
    return Result.error(new BadParameters("bad parameters"));
  else
    return Result.error(new NotFound("customer not found"));
}

BadParameters and NotFound are entities for our business logic that contain the desired information for handling these responses.

For handling the result we could just use the methods isError() and getData().

Result result = operation();

if(result.isError()){
  //do something with the error
}else{
  Customer customer = result.getValue();
}

Finally we use in our mapping a generic ResponseEntity we could return the wrapper value without needing to understand what contains.

For example:

@GetMapping("/customer/{id}")
  public ResponseEntity<?> get(@PathVariable() int id) {
  final Result result = customerService.get(id);
  final HttpStatus status = getStatus(result);

  return new ResponseEntity<>(result.getValue(), status);
}

Since we may like to return different HTTP status, based on the error contained, we could create a helper that use the type of the class held on the wrapper.

private HttpStatus getStatus(final Result result){
  if (result.isError()) {
    if (result.getValue() instanceof NotFound)
      return HttpStatus.NOT_FOUND;
    else
      return HttpStatus.BAD_REQUEST;
  } else return HttpStatus.OK;
}

runing

To just run the example microservice you could just do from the command line:

$ mvnw spring-boot run

To test the output when sending a correct customer id:

$ curl -i http://localhost:8080/customer/1
HTTP/1.1 200
X-Application-Context: application
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 31 Jan 2018 09:33:01 GMT

{
  "data" : "super customer",
  "id" : 1
}

To test the output when sending a invalid customer id

$curl -i http://localhost:8080/customer/-1
 HTTP/1.1 400
 X-Application-Context: application
 Content-Type: application/json;charset=UTF-8
 Transfer-Encoding: chunked
 Date: Wed, 31 Jan 2018 09:34:03 GMT
 Connection: close

 {
   "message" : "bad parameters"
 }

To test the output when sending a not found customer id

$ curl -i http://localhost:8080/customer/2
HTTP/1.1 404
X-Application-Context: application
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 31 Jan 2018 09:34:48 GMT

{
  "message" : "customer not found"
}

microserviceserrorhandling's People

Contributors

juan-medina avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

nitinls

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.