How to handle exceptions elegant Spring project

What is abnormal?

Java中的异常(Exception)又称为例外,是一个在程序执行期间发生的事件,它中断正在执行的程序的正常指令流。
复制代码

The most common statement is, during program execution, there have been various cases interrupting the running program. For example you are using a divide function calculator, with the removal of 1 to 0, since 0 is not used as the dividend, so the abnormal operation is a. In a program, the programmer errors may occur in unexpected circumstances or environment outside the controllable range of the programmer, for example, bad data user, trying to open a file does not exist, and the like.

这里再做一下java中的异常分类:
复制代码

In Java, all exceptions have a common ancestor Throwable (throwable). Throwable specify the code available in any common problems anomalous propagation mechanism of transmission through Java applications.

Throwable:有两个重要的子类:Exception(异常)和Error(错误),二者都是Java异常处理的重要子类,各自都包含大量子类。异常和错误的区别是:异常能被程序本身可以处理,错误是无法处理。

Exception(异常):是程序本身可以处理的异常。
Exception类有一个重要的子类RuntimeException。RuntimeException类及其子类表示“JVM常用操作”引发的错误。例如,若试图使用空值对象引用、除数为零或数组越界,则分别引发运行时异常(NullPointerException、ArithmeticException)和 ArrayIndexOutOfBoundException。
复制代码

Exception (abnormal) divided into two categories: Unusual and non-runtime exception (the compiler abnormal) is running. Program should be to deal with these exceptions as possible.

1.运行时异常:都是RuntimeException类及其子类异常,如NullPointerException(空指针异常)、IndexOutOfBoundsException(下标越界异常)等,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理。这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生。运行时异常的特点是Java编译器不会检查它,也就是说,当程序中可能出现这类异常,即使没有用try-catch语句捕获它,也没有用throws子句声明抛出它,也会编译通过。

2.非运行时异常 (编译异常):是RuntimeException以外的异常,类型上都属于Exception类及其子类。从程序语法角度讲是必须进行处理的异常,如果不处理,程序就不能编译通过。如IOException、SQLException等以及用户自定义的Exception异常,一般情况下不自定义检查异常。
复制代码

We deal with unusual ways to uphold a fundamental principle, known exception we should try to capture the process, an unknown exception is thrown outward, external services provided to dispose of their own exceptions, in principle, should reduce foreign direct exposure exception. The above are some of the theoretical introduction, the following is the code in part, directly to tell you how to use the global anomalies in the project capture mechanism and the front page to interact.

First we create an abstract base exception class, implement different exception handling differences

public abstract class BaseException extends RuntimeException {

public BaseException(int code) {
    super(String.valueOf(code));
}

public BaseException(int code, Throwable cause) {
    super(String.valueOf(code), cause);
}

public BaseException(String msg) {
    super(msg);
}

public BaseException(String msg, Throwable cause) {
    super(msg, cause);
}

protected BaseException(int code, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    super(String.valueOf(code), cause, enableSuppression, writableStackTrace);
}
复制代码

}

A custom exception class, business exceptions all with the exception caught. Of course, you may also need their own project, Custom different exception types. For example, said abnormal operation of a system is defined, in terms of data handling exceptions like.

public class BusinessException extends BaseException {

public BusinessException(int code) {
    super(code);
}

public BusinessException(int code, Throwable cause) {
    super(code, cause);
}

public BusinessException(String msg, Throwable cause) {
    super(msg, cause);
}

public BusinessException(String msg) {
    super(msg);
}

protected BusinessException(int code, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    super(code, cause, enableSuppression, writableStackTrace);
}
复制代码

}

public class DBException extends BaseException {

public BusinessException(int code) {
    super(code);
}

public BusinessException(int code, Throwable cause) {
    super(code, cause);
}

public BusinessException(String msg, Throwable cause) {
    super(msg, cause);
}

public BusinessException(String msg) {
    super(msg);
}

protected BusinessException(int code, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    super(code, cause, enableSuppression, writableStackTrace);
}
复制代码

}

public class ResponseObject {

/**
 * 正常返回的状态码
 */
private static final String NORMAL_CODE = "0";

/**
 * 正常返回的描述
 */
private static final String NORMAL_MSG = "正常";

/**
 * 接口返回码
 */
private String statusCode;

/**
 * 接口返回描述
 */
private String msg;

/**
 * 接口响应的实际数据
 */
private Object data;

public String getStatusCode() {
    return statusCode;
}

public void setStatusCode(String statusCode) {
    this.statusCode = statusCode;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

public Object getData() {
    return data;
}

public void setData(Object data) {
    this.data = data;
}

public ResponseObject(String statusCode, String msg) {
    this.statusCode = statusCode;
    this.msg = msg;
}
复制代码

}

Class method, a method in which annotation @ControllerAdvice @ExceptionHandler annotated with a modified method, will correspond to the abnormal processing corresponding

@ControllerAdvice

public class GlobalExceptionHandler {

/**
 * 业务操作异常
 */
private static final String UNNORMAL_EXCEPTION_CODE = "100001";

/**
 * 数据库查询异常
 */
private static final String DB_EXCEPTION_CODE = "100002";

@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ResponseObject businessExceptionHandler(HttpServletRequest req, Exception e) {
    String code = UNNORMAL_EXCEPTION_CODE;
    String msg = "业务操作异常";
    return new ResponseObject(code, msg);
}
@ExceptionHandler(value = DBException.class)
@ResponseBody
public ResponseObject businessExceptionHandler(HttpServletRequest req, Exception e) {
    String code = DB_EXCEPTION_CODE;
    String msg = "数据库查询异常";
    return new ResponseObject(code, msg);
}
复制代码

}

Expand on these two notes of explanation

// The role of the object as a method comment

@Target ({ElementType.METHOD}) // valid at runtime

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface ExceptionHandler {

//value()可以指定异常类

Class<? extends Throwable>[] value() default {};
复制代码

}

@Target({ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Documented

// bean objects spring to generate management

@Component

public @interface ControllerAdvice {

@AliasFor("basePackages")

String[] value() default {};

@AliasFor("value")
String[] basePackages() default {};

Class<?>[] basePackageClasses() default {};

Class<?>[] assignableTypes() default {};

Class<? extends Annotation>[] annotations() default {};
复制代码

}

note

1. does not have to throw an exception to the controller layer itself is processed GlobalExceptionHandler, as long as an exception is thrown from contoller last layer can be processed to a global exception handler.

2. The method of asynchronous exception handling exceptions is not global.

3. If an exception is thrown in the code try / catch caught, will not be GlobalExceptionHandler handled.

to sum up:

advantage

Reduce code redundancy, the code for maintenance

Shortcoming

Can only handle exceptions thrown controller layer, for example,

Exception Interceptor (interceptor) layer, an abnormality in the timer task, abnormal asynchronous method, does not process.

Guess you like

Origin juejin.im/post/5d478bdc6fb9a06b1e7f2001