com.kasinf.framework.rest.web.controller.SearchableExceptionHandler Maven / Gradle / Ivy
The newest version!
package com.kasinf.framework.rest.web.controller;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.kasinf.framework.core.exception.BaseException;
import com.kasinf.framework.core.exception.ValidateException;
import com.kasinf.framework.core.response.R;
import com.kasinf.framework.core.util.MessageUtils;
import com.kasinf.framework.rest.config.SearchableConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Collections;
import java.util.Map;
/**
* @author lkhsh
* 全局异常处理类
*/
@Slf4j
@ControllerAdvice
public class SearchableExceptionHandler {
private final Map httpCode;
public SearchableExceptionHandler(SearchableConfiguration configuration) {
this.httpCode = configuration.getHttpCode();
}
@ExceptionHandler(ValidateException.class)
@ResponseBody
public R setErrorResponse(ValidateException validateException) {
log.error(validateException.getMessage(), validateException);
int code = httpCode.get(HttpStatus.BAD_REQUEST);
String msg = MessageUtils.message("http.msg." + code, "校验异常!");
return R.error(code, msg, Collections.singleton(validateException.getErrors()));
}
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public R setRuntimeErrorResponse(RuntimeException error) {
log.error(error.getMessage(), error);
int code = httpCode.get(HttpStatus.SERVICE_UNAVAILABLE);
String msg = MessageUtils.message("http.msg." + code, "内部错误!");
return R.error(code, msg, ExceptionUtil.stacktraceToOneLineString(error));
}
@ExceptionHandler(BaseException.class)
@ResponseBody
public R setBaseErrorResponse(BaseException error) {
log.error(error.getMessage(), error);
int code = httpCode.get(HttpStatus.SERVICE_UNAVAILABLE);
String msg = error.getMessage();
return R.error(code, msg, ExceptionUtil.stacktraceToOneLineString(error));
}
}