当前位置:网站首页>How to handle code exceptions gracefully with assertion ideas
How to handle code exceptions gracefully with assertion ideas
2022-07-18 15:45:00 【Chat with Lao Wang】
Catalog
2、 How to customize assertions
2.1 Custom assertion interface
2.2 Custom response enumeration interface
2.3 Custom response enumeration interface
2.4 Basic exception information encapsulation
2.5 Business exception information encapsulation
2.6 Business assertion encapsulation
1、Assert( Assertion )
Assert Everyone should be familiar with , For example Spring In the project , Unit tests often use org.springframework.util.Assert package .
Assert the role of exception handling : Make coding exception handling more elegant .
With grace Assert Method to verify business exceptions , Developers can focus more on business logic , Instead of spending a lot of energy writing redundant if else and try catch Code block . adopt Assest The way can be eliminated 90% The above try catch Code block .
Take a look at the following two pieces of code , Which one do you think is more silky ?
public void testOrder2() {
// ... Omit
Order order = orderDao.selectById(orderId);
Assert.notNull(order, " The order does not exist .");
}public void testOrder2() {
// ... Omit
Order order = orderDao.selectById(orderId);
if (order == null) {
throw new IllegalArgumentException(" The order does not exist .");
}
}The first way to judge non emptiness is relatively elegant , The second rule of writing is if {...} Code block , Obvious redundancy and procrastination . that Assert.notNull() How to realize the bottom layer ?
public abstract class Assert {
public Assert() {
}
public static void notNull(@Nullable Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
}You can see ,Assert In fact, it is to help us to if {...} It encapsulates . Simple though , But there's no denying it , The coding experience will rise a lot .
Based on this idea , We might as well imitate org.springframework.util.Assert Write an assertion class , But the exception thrown after the assertion fails is not IllegalArgumentException These built-in exceptions , It's our own definition of the anomaly .
2、 How to customize assertions
2.1 Custom assertion interface
Custom assertion interface , Encapsulate exception types .
package com.example.demo.exception;
/**
* Custom assertion
*/
public interface CustomAssert {
BaseException newException();
/**
* Create exception
*
* @param args
* @return
*/
BaseException newException(Object... args);
/**
* Create exception
*
* @param t
* @param args
* @return
*/
BaseException newException(Throwable t, Object... args);
/**
* Object of assertion obj Non empty . If the object obj It's empty , Throw an exception
*/
default void assertNotNull() {
throw newException();
}
/**
* Object of assertion obj Non empty . If the object obj It's empty , Throw an exception
*
* @param obj The object to be judged
*/
default void assertNotNull(Object obj) {
if (obj == null) {
throw newException(obj);
}
}
/**
* Object of assertion obj Non empty . If the object obj It's empty , Throw an exception
* Abnormal information message It supports parameter passing , Avoid string concatenation before judging
* @param obj The object to be judged
* @param args message Parameter list for placeholders
*/
default void assertNotNull(Object obj, Object... args) {
if (obj == null) {
throw newException(args);
}
}
}When the assertion fails , The exception thrown is not a specific exception , It's up to you 2 individual newException Interface method provision . Because the exceptions in business logic are basically corresponding to specific scenarios , For example, according to the order id Get order information , The query result is null, The exception thrown at this time may be OrderNotFoundException, And there are specific exception codes ( such as 100) And exception information “ Order information does not exist ”.
So what exceptions are thrown specifically , from CustomAssert The implementation class of .
2.2 Custom response enumeration interface
Define unified return exception codes and exception information . take code and message Locate as enum type , It is convenient for unified management of exception attributes and parameter transmission .
package com.example.demo.exception;
/**
* Response information enumeration value template
**/
public interface IResponseEnum {
/**
* Error code
* @return Error code
*/
int getCode();
/**
* error message
* @return error message
*/
String getMessage();
}2.3 Custom response enumeration interface
Subsequent businesses can implement the exception types required for extension based on this enumeration .
package com.example.demo.exception;
/**
* Extensible exception enumeration
*/
public enum ResponseEnum implements BusinessExceptionAssert{
/** System exception **/
SYSTEM_EXCEPTION(100, " System exception "),
/** Object cannot be empty **/
OBJECT_IS_NULL(200, "{0}")
;
/**
* Return code
*/
private int code;
/**
* Return message
*/
private String message;
ResponseEnum(int code, String message) {
this.code = code;
this.message = message;
}
@Override
public int getCode() {
return this.code;
}
@Override
public String getMessage() {
return this.message;
}
}2.4 Basic exception information encapsulation
Unified return exception class .
package com.example.demo.exception;
/**
* Basic exception information encapsulation
*/
public class BaseException extends RuntimeException {
/**
* Error code
*/
private int errorCode;
/**
* error message
*/
private String errorMessage;
/**
* The ginseng
*/
private Object errorResult;
public BaseException(IResponseEnum iResponseEnum, String msg) {
super(msg);
this.errorCode = iResponseEnum.getCode();
this.errorMessage = iResponseEnum.getMessage();
this.errorResult = msg;
}
public BaseException(IResponseEnum iResponseEnum, Object[] args, String msg) {
super(msg);
this.errorCode = iResponseEnum.getCode();
this.errorMessage = iResponseEnum.getMessage();
this.errorResult = msg;
}
public BaseException(IResponseEnum iResponseEnum, Object[] args, String msg, Throwable t) {
super(msg);
this.errorCode = iResponseEnum.getCode();
this.errorMessage = iResponseEnum.getMessage();
this.errorResult = msg;
}
public BaseException(IResponseEnum iResponseEnum) {
super(iResponseEnum.getMessage());
this.errorCode = iResponseEnum.getCode();
this.errorMessage = iResponseEnum.getMessage();
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public Object getErrorResult() {
return errorResult;
}
}2.5 Business exception information encapsulation
Business exception implementation class .
package com.example.demo.exception;
/**
* Business exceptions
**/
public class BusinessException extends BaseException {
private static final long serialVersionUID = 1L;
public BusinessException(IResponseEnum resp, Object[] args, String msg, Throwable t) {
super(resp, null);
}
public BusinessException(IResponseEnum resp, String os) {
super(resp, os);
}
public BusinessException(BusinessExceptionAssert businessExceptionAssert, Object[] args, String msg) {
super(businessExceptionAssert, args, msg);
}
public BusinessException(BusinessExceptionAssert businessExceptionAssert, Object[] args, String msg, Throwable t) {
super(businessExceptionAssert, args, msg, t);
}
}2.6 Business assertion encapsulation
package com.example.demo.exception;
import java.text.MessageFormat;
public interface BusinessExceptionAssert extends IResponseEnum, CustomAssert {
@Override
default BaseException newException() {
return new BusinessException(this, this.getMessage());
}
@Override
default BaseException newException(Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg, t);
}
}2.7 Test class
package com.example.demo.exception;
/**
* The test method
*/
public class TestMain {
public static void main(String[] args) {
// ResponseEnum.SYSTEM_EXCEPTION.assertNotNull(); // System exception
ResponseEnum.OBJECT_IS_NULL.assertNotNull(null," Order object cannot be empty "); // The object is not empty
}
}summary : We can see from the above example , The actual business code basically does not need too much redundancy try catch Block. . The above custom assertion mainly refers to Spring in Assets How to implement , It encapsulates the exception handling methods often used in business in a friendly way . In addition, for exceptions in different business scenarios , Uniformly manage through exception enumeration types , It also reflects good scalability .
Official account , Get all interview materials for free !
边栏推荐
- 【LeetCode】11. Lowest common ancestor of a binary search tree
- Vulnhub-dc9 learning notes
- Find active SQL connections in SQL Server
- Optimization of AI model structure based on nvidiagpu
- Special testing of mobile applications [reprint ~ Test Engineer full stack technology advancement and practice]
- 免费SSL证书申请及部署实践
- Jiulian technology development board is officially integrated into the openharmony backbone
- Top n% data before SQL calculation
- zabbix详细介绍
- 爱科荣获2022年红点奖:设计概念奖
猜你喜欢

High performance timer

R language - color selection and setting

基于时间戳的唯一标识符的轻量级跟踪方法

Onnx model tensor shapes information and flops statistical tools

史上最全mysql!拼命整理

Jiulian technology development board is officially integrated into the openharmony backbone

Fun ping command

The most complete MySQL in history! Desperately tidy up

【LeetCode】11. Lowest common ancestor of a binary search tree

Know Baidu AI development platform
随机推荐
从小米10发布来看编译优化
R语言---颜色选择和设置
无线通信中LoRa技术特点
Cron expressions are executed from Monday to Friday and only on Saturday and Sunday
CV2. Setmousecallback() displays the pixel value and position of the mouse click image
C language -- the implementation of common string functions
HMS core graphics and image technology shows the latest functions and application scenarios, and accelerates the construction of digital intelligence life
1111111111111
C1083: 无法打开包括文件:“corecrt.h”
. Net to publish the project to the server in the form of file
AGCO won the 2022 red dot award: design concept award
常用测试用例设计方法之判定表法详解
C1083: unable to open include file: 'corecrt.h'
Differences among key, primary key, unique key and index in MySQL
AcWing 135. 最大子序和
Airiot low code development platform, 10 minutes to build the Internet of things system
Redis cluster test
Lscale theme emlog background management panel theme source code
leetcode:378. 有序矩阵中第 K 小的元素
笔记-如何在稀烂的数据中做深度学习