Exceptions vs Error Codes (异常还是错误代码)

 Excpetion is a situation when a piece of code encounters some unexpected problem while running, and couldn't accomplish its task. The emphasis on the “unexpected“ is important, because it eliminates some scenarios that, from first glance, may require throwing an exception, but I think they really shouldn't do that.

Error, in contrast, is a situation when a piece of code encounters an expected problem while running, and couldn't accomplish its task. Again, the emphasis is important. As strange as it may sound, there are expected problems that should be taken care of while running.

Let's look at a sample:

The read() method of the (SQL | OleDB)DataReader. This method returns either true or false. False is returned when there are no more rows to read from. If we'll stick only to the “can't accomplish task“ definition, then the method should throw something like EndOfDataException. But in this case an error code is in order, since this is a (very) expected situation. I mean, you did expect the data to come to its end finally, didn't you?

But - if the connection to the database was terminated suddenly, then this method will throw an exception, since this should not happen, and it is very unexpected (and unwelcome) situation.

If we utilize this definition, we'll find out that the performance penalty of throwing exceptions is insignificant. The application has encountered some unexpected error which it does not know how to handle, and the best thing to do now is write something to log file, close all resources, go to the nearest shelter and pray. Performance are really meaningless in this situation.

It's important to avoid using Exceptions as Flags - “Hey, something happened. Now tell us how to go on.“ For example, In Ashish disappearing post, the following code sample is written:

===========================================================

My application, a web-service reads a string column from the database. 50% of the time this string is a datetime, 50% it’s not. In .net 1.0 /1.1 it is easy for this to lead to code like the following..

 DateTime d = DateTime.MinValue;

Try

{

            D = DateTime.Parse( string );

}

Catch( InvalidCastExcpetion )

{

            // swallow

}

 Put this in a loop in a middle tier component ( say processing a recordset ), and load up the server. You’ll generate 1000s of exceptions per second in the asp.net wp, and can easily drop throughput by an order of magnitude. There are a number of internal and external applications I’ve seen coded exactly like this. It’s hard to argue with the correctness of the DateTime.Parse() implementation from a purist pov, but the ramifications can be a lot of money spent on additional hardware by the consumer of the api.

=========================================================================

Couldn't say it better. Again, Exceptions should be used ONLY when something unexpected happened, and the process (the logical one, not the physical) should stop.

There is another reason for not using error codes, and that's the Return Value Type dilemma.When talking about “Error Code”, it's usually a number (eg. -1) or some kind of String. Our method won't necessarily return this type. It may return DataSet, Date, Custom objects or anything else. If we would like to be able always to return error code, and we'll try to utilize it for every problem, even the unexpected ones, each and every function will have to have “Object” as its return type. Another alternative is to have another ByRef argument which will hold the error code, but this will mess up the code and add unnecessary cumbersomeness to the method's interface.

So, to coclude:

When a method has some pre-defined situations when it might won't be able to accomplish its task, it should return an Error Code.

When a method encounters some unexpected problem which prevents it to accomplish its task, it should throw an Exception.

转载于:https://www.cnblogs.com/Wind-Snail/archive/2008/01/16/1041230.html

### 实现 Spring Boot 多模块项目的全局异常处理 在构建复杂的多模块应用程序时,确保一致性和可维护性的全局异常处理机制至关重要。通过定义统一的错误响应结构和集中化的异常处理器,可以提高系统的健壮性和用户体验。 #### 使用 `@ControllerAdvice` 注解创建全局异常处理器类 为了捕获整个应用中的未处理异常并提供友好的反馈给客户端,推荐使用带有 `@ControllerAdvice` 的控制器增强器来实现全局异常管理功能[^1]: ```java import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice(basePackages = {"com.example.moduleA", "com.example.moduleB"}) public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleException(Exception ex) { ErrorResponse errorResponse = new ErrorResponse( HttpStatus.INTERNAL_SERVER_ERROR.value(), "Unexpected server error", System.currentTimeMillis() ); return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); } } ``` 此方法允许开发者指定哪些包下的异常会被该顾问所拦截,并返回标准化的 JSON 错误消息体。 #### 定义自定义异常及其对应的 HTTP 响应状态码映射表 对于业务逻辑层面可能出现的具体场景,建议封装成特定类型的运行期异常,并为其分配合适的HTTP状态码以便于前端解析: ```java // Custom exceptions with status codes mapping public class ResourceNotFoundException extends RuntimeException { private final int statusCode; public ResourceNotFoundException(String message, int statusCode){ super(message); this.statusCode = statusCode; } // Getter for statusCode... } // Update the global handler accordingly @ExceptionHandler(ResourceNotFoundException.class) protected ResponseEntity<Object> handleResourceNotFound(RuntimeException ex) { ApiError apiError = new ApiError(((ResourceNotFoundException)ex).getStatusCode(), ex.getMessage()); return buildResponseEntity(apiError); } ``` 这样做的好处是可以更精确地传达问题所在以及指导下一步操作方向。 #### 配置跨多个子模块共享相同的异常处理策略 当项目被拆分为若干独立但又相互关联的小型服务单元时,可以通过引入公共依赖库的方式让各个部分都能继承同样的异常捕捉行为而无需重复编写相同代码片段。这不仅减少了冗余还增强了协作效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值