springboot 异常处理
关键字
1、自定义异常类
package com.example.learning.common.exception;
import lombok.Data;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
@Data
public class LearningException extends RuntimeException {
protected String errorCode;
protected String[] errorMsg;
public LearningException(String key, String... values) {
this.errorCode = key;
this.errorMsg = values;
}
}
2、定义异常处理handler
package com.example.learning.common.exception;
import com.example.learning.common.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.text.MessageFormat;
import java.util.Locale;
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {
@Autowired
private MessageSource messageSource;
@ExceptionHandler(value = LearningException.class)
public ResultVo LearningExceptionHandler(LearningException e){
String message = messageSource.getMessage(e.getErrorCode(), null, Locale.getDefault());
String format = MessageFormat.format(message, e.getErrorMsg());
return ResultVo.error(format);
}
}
3、添加配置
spring:
messages:
basename: exception/error
encoding: UTF-8
4、resource目录下创建error.properties
system.exception.500=系统异常{0},{1}