简体   繁体   English

建模异常和处理服务器应用程序中的 http 代码

[英]Modelling exceptions & Handling http codes inside a server application

I am working on a spring boot application, which makes http calls to multiple external services, aggregates and returns the response to the frontend.我正在开发一个 spring 启动应用程序,它使 http 调用多个外部服务,聚合并将响应返回到前端。

Here's the current structure of my project:这是我项目的当前结构:

RouteController -> Handler -> ServiceLayer
  • RouteController routes to different handlers RouteController 路由到不同的处理程序
  • Handler makes call to multiple services, performs aggregates and returns response. Handler 调用多个服务,执行聚合并返回响应。
  • Different ServiceLayers for each service call.每个服务调用都有不同的 ServiceLayers。
  • Handler can return partial responses, if one service call fails it'll return the response of other calls.处理程序可以返回部分响应,如果一个服务调用失败,它将返回其他调用的响应。
  • I have not added class/controller level exception handler as partial response can also be returned.我没有添加类/控制器级别的异常处理程序,因为也可以返回部分响应。

Note - This application will always send a Http 200 response, unless all service calls fail.注意- 此应用程序将始终发送 Http 200 响应,除非所有服务调用都失败。
Spring exception handling https://www.baeldung.com/exception-handling-for-rest-with-spring is for class/controller level and conveys the Http response code to the client. Spring异常处理What I'm looking for here is exception handling inside the application.我在这里寻找的是应用程序内部的异常处理。

I'm trying to add exception handling in this service, and there doesn't seem to be a clear concise rule.我正在尝试在此服务中添加异常处理,并且似乎没有明确简洁的规则。

This is a custom exception i have created for any dependency failure -这是我为任何依赖失败创建的自定义异常 -

class DependencyException : RuntimeException {
    constructor() : super()
    constructor(message: String?) : super(message)
    constructor(cause: Exception?) : super(cause)
    constructor(message: String?, cause: Exception?) : super(message, cause)
}

Here's the code in service layer making a call to UserService -这是调用 UserService 的服务层中的代码 -

fun getUsers(): List<User>? {
        logger.info { "entered: getUsers " }
        val response = userControllerApiClient.getUsers()

        when (response.statusCode.is2xxSuccessful) {
            true -> return response.body?.users
            false ->  throw DependencyException()
        }
    }

Have used org.springframework.http library for http calls.已使用org.springframework.http库进行 http 调用。

There are a few questions I couldn't find a clear answer of -有几个问题我找不到明确的答案——

  • When should a service write its own exceptions?服务何时应该编写自己的异常?
  • When to use kotlin/java standard lib existing exceptions?何时使用 kotlin/java 标准库现有异常?
  • Should you propagate spring http exceptions to handler/controller layer?您是否应该将 spring http 异常传播到处理程序/控制器层?
  • Is the scope of dependency exception above too large?上面的依赖异常的scope是不是太大了?
  • Should 4xx,5xx error codes be converted to different custom exception for internal handling? 4xx,5xx 错误代码是否应该转换为不同的自定义异常以进行内部处理? (And also different handling of different codes in each series? ) (以及每个系列中不同代码的不同处理?)
  • What's the best way you'd recommend for handling exceptions in this project?您建议在此项目中处理异常的最佳方法是什么?

Hi for your questions:您好,您的问题:

  1. When should a service write its own exceptions?服务何时应该编写自己的异常? --> -->

it depends in your business logic for example you have a service layer to update a user, you should find it by ID, if user not found you should throw an exception这取决于您的业务逻辑,例如您有一个服务层来更新用户,您应该通过 ID 找到它,如果找不到用户,您应该抛出异常

  1. When to use kotlin/java standard lib existing exceptions?何时使用 kotlin/java 标准库现有异常?

if you are using spring-boot is a framework to provide for you ready libs and APIS to handle all you can check this link https://www.baeldung.com/exception-handling-for-rest-with-spring如果您使用 spring-boot 是一个框架,为您提供现成的库和 APIS 来处理所有您可以查看此链接https://www.baeldung.com/exception-handling-for-rest-with-spring

  1. Should you propagate spring Http exceptions to handler/controller layer?您是否应该将 spring Http 异常传播到处理程序/控制器层?

Yes;是的; because the controller is responsible for handling the Http exceptions, the service the business layer因为controller负责处理Http的异常,业务层的service

  1. Is the scope of dependency exception above too large?上面的依赖异常的scope是不是太大了?

I didn't understand this question我没看懂这个问题

  1. Should 4xx,5xx error codes be converted to different custom exception types? 4xx,5xx 错误代码是否应该转换为不同的自定义异常类型? (And also different handling of different codes in each series? ) (以及每个系列中不同代码的不同处理?)

No it's not necessary, it's recommended to return the Http error code with custom message for the client to understand exception error cause不需要,建议返回 Http 错误代码和自定义消息,以便客户端了解异常错误原因

  1. What's the best way you'd recommend for handling exceptions in this project?您建议在此项目中处理异常的最佳方法是什么?

I recommend following jhiptser spring boot project structure, https://www.jhipster.tech/managing-server-errors/我推荐遵循 jhiptser spring 引导项目结构, https://www.jhipster.tech/managing-server-errors/

  1. When should a service write its own exceptions?服务何时应该编写自己的异常? Whenever existing exceptions in standard library don't cover your use case, or when you want to add more details in an exception.每当标准库中的现有异常不涵盖您的用例时,或者当您想在异常中添加更多详细信息时。

  2. When to use kotlin/java standard lib existing exceptions?何时使用 kotlin/java 标准库现有异常? Same as above, don't try to reinvent the wheel.同上,不要试图重新发明轮子。 Like,Use IllegalArgumentException instead of creating you own InvalidRequestException.比如,使用 IllegalArgumentException 而不是创建您自己的 InvalidRequestException。 Take a look here - https://programming.guide/java/list-of-java-exceptions.html看看这里 - https://programming.guide/java/list-of-java-exceptions.html

  3. Should you propagate spring Http exceptions to handler/controller layer?您是否应该将 spring Http 异常传播到处理程序/控制器层? I'd suggest not propagating exceptions of any external framework to your controller.我建议不要将任何外部框架的异常传播到您的 controller。 Rather, write your own exceptions, and use as much existing ones from Java.lang.相反,编写您自己的异常,并尽可能多地使用 Java.lang 中的现有异常。 Http exceptions should stay for where they are meant for, Request/Response layers. Http 异常应该保留在它们的预期位置,即请求/响应层。
  4. Is the scope of dependency exception above too large?上面的依赖异常的scope是不是太大了? Dependency Exception here is too broad, What if your application has to treat different Http codes in different ways.这里的依赖异常太宽泛了,如果您的应用程序必须以不同的方式处理不同的 Http 代码怎么办。 How will you handler manage that?您将如何处理该问题?
  5. Should 4xx,5xx error codes be converted to different custom exception types? 4xx,5xx 错误代码是否应该转换为不同的自定义异常类型? (And also different handling of different codes in each series? ) Depends a lot on what the client wants. (以及每个系列中不同代码的不同处理方式?)很大程度上取决于客户的需求。 In your case as you have mentioned, you are handling them at orchestration layer and suppressing them.正如您所提到的,在您的情况下,您正在编排层处理它们并抑制它们。 Do you see this implementation to change in future, and in how far?您是否认为这种实现在未来会发生变化,以及变化多远? First step I'd suggest is to at least map 4xx and 5xx errors to different exceptions.我建议的第一步是至少 map 4xx 和 5xx 错误到不同的异常。 Take a closer look, and see which ones you'd want to retry/recover from and derive another type from there.仔细看看,看看你想重试/恢复哪些,并从中派生另一种类型。

Here's a few resourced I think you should look at -这里有一些资源我认为你应该看看 -

https://itnext.io/graceful-error-handling-in-rest-driven-web-applications-d4209b4937aa https://itnext.io/graceful-error-handling-in-rest-driven-web-applications-d4209b4937aa

https://github.com/cloudendpoints/endpoints-java/blob/master/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceException.java https://github.com/cloudendpoints/endpoints-java/blob/master/endpoints-framework/src/main/java/com/google/api/server/spi/ServiceException.java

REST API error return good practices REST API 错误返回良好做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM