spring bootはあなたに全体の異常な処理を教えます.
spring bootグローバル異常処理
全体の異常を処理するには3ステップに分けて行う必要があります.カスタム異常エニュメレーション カスタム異常 spring book AOP異常処理 以下の私の書いたのは比較的に簡単です.自分の状況に合わせて処理したいです.ここでは簡単にコード思想を書きます.
1カスタム同じ列挙
全体の異常を処理するには3ステップに分けて行う必要があります.
1カスタム同じ列挙
public enum WebExceptionEnum {
/**
* SYS_ERROR
* UNKNOWN_ERROR
* SERVICE_INVOKE_ERROR
* ILLEGAL_ARGS
*/
SYS_ERROR("SYS_ERROR", " "),
UNKNOWN_ERROR("UNKNOWN_ERROR", " "),
SERVICE_INVOKE_ERROR("SERVICE_INVOKE_ERROR", " "),
ILLEGAL_ARGS("ILLEGAL_ARGS", " ");
private String exception;
private String massage;
WebExceptionEnum(String exception, String massage) {
this.exception = exception;
this.massage = massage;
}
public String getException() {
return exception;
}
public String getMassage() {
return massage;
}
public static WebExceptionEnum getWebException(String exception) {
for (WebExceptionEnum results : WebExceptionEnum.values()) {
if (results.getException().equals(exception)) {
return results;
}
}
return null;
}
}
2カスタム異常public class MessageCenterException extends RuntimeException{
private static final long serialVersionUID = -8581672033133636908L;
//
private WebExceptionEnum exceptionEnum;
//set
private void setExceptionEnum(WebExceptionEnum exceptionEnum){
this.exceptionEnum = exceptionEnum;
}
//
public WebExceptionEnum getExceptionEnum(){
return exceptionEnum;
}
//
public MessageCenterException(WebExceptionEnum exceptionEnum){
super(exceptionEnum.getMassage());
this.setExceptionEnum(exceptionEnum);
}
//
@Override
public String getMessage() {
return exceptionEnum.getMassage();
}
}
3グローバル異常処理@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//
//
/**
* oracle
*
*
*/
// value
@ExceptionHandler(MessageCenterException.class)
public Result baseException(HttpServletRequest request, MessageCenterException ex) {
log.error(ex.getMessage());
return ErrorResult.error(ex.getMessage());
}
}
その後、プロジェクトの中でこれを返します.普通の異常類で十分です.複雑ならば、拡張できます.