SpringBoot defines an elegant global unified Restful API response framework five

Not much gossip, continue to optimize the global unified Restful API response framework to make the common interface of the project extensible.

If you haven't read the previous articles, please read the previous articles

SpringBoot defines an elegant global unified Restful API response framework

SpringBoot defines an elegant global unified Restful API response framework 2

SpringBoot defines an elegant global unified Restful API response framework three

SpringBoot defines an elegant global unified Restful API response framework four

Here to solve the problem left in the previous article, how to realize the internationalization of interface errors. And the previous error message is not very friendly

We can further abstract the common exception interface .

Exception information should consist of fixed exception encoding information plus detailed error custom information.

The last error message in the last article is still not friendly and specific enough. We can specify which field

There is also an exception returned by an unknown error. It is mentioned here that we need to connect our own log output processing in the global exception handling. We just simply print it on the console. definitely not

If you do not do any processing in the project, the log processing logic of the Tomcat server will be used by default, and the output will be output to the
catalina file . Let's deal with this problem here.

public error exception class

Custom exception classes inherit runtime exceptions. Custom error code, and error message enumeration

/**
* @author 公众号 程序员三时
* @version 1.0
* @date 2023/4/29 00:15
* @webSite https://github.com/coder-amiao
* 通用业务异常封装
*/
@Data
public class BusinessException extends RuntimeException {
    
    
   /**
    * 自定义异常编码
    */
   private String code;

   public BusinessException(String code, String message) {
    
    
       super(message);
       this.code = code;
   }

   public BusinessException(ResultCode resultCodeEnum) {
    
    
       super(resultCodeEnum.getMessage());
       this.code = resultCodeEnum.getCode();
   }

   public BusinessException(ResultCode resultCodeEnum, String msg) {
    
    
       super(resultCodeEnum.getMessage() +" " +msg);
       this.code = resultCodeEnum.getCode();
   }
}

The same goes for other exception classes

Here we mainly talk about how to output the error log to the specified log file of the specified server path

Log files are divided by type and time, one per day according to the specified size

In this way, it is convenient to query the error log by yourself

log configuration file

logback-spring.xml springboot convention configuration name, can read and load property files

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>shop-api</contextName>
    <!--定义日志文件的存储地址 从springboot配置文件中获取路径-->
    <springProperty scope="context" name="LOG_PATH" source="logging.file.path"/>
    <!--springboot配置文件中获取日志级别-->
    <springProperty scope="context" name="LOG_LEVEL" source="logging.level.root"/>
    <!-- <property name="log.path" value="log" />-->
    <property name="log.maxHistory" value="90" />
    <property name="log.colorPattern" value="%magenta(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%-5level) %yellow(%thread) %green(%logger) %msg%n"/>
    <property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %thread %logger %msg%n"/>

    <!--输出到控制台-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${log.colorPattern}</pattern>
        </encoder>
    </appender>

    <!--输出到文件-->
    <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/info/info.%d{yyyy-MM-dd}-%i.log</fileNamePattern>
            <maxFileSize>3MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/error/error.%d{yyyy-MM-dd}-%i.log</fileNamePattern>
            <maxFileSize>3MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <root level="debug">
        <appender-ref ref="console" />
    </root>

    <root level="info">
        <appender-ref ref="file_info" />
        <appender-ref ref="file_error" />
    </root>
</configuration>

Proxy has been updated to the github repository scaffolding project

Pay attention to the official account, the programmer will continue to output high-quality content at three o'clock , hoping to bring you some inspiration and help

Guess you like

Origin blog.csdn.net/u011738045/article/details/130964688