com.github.rexsheng.springboot.faster.system.exception.ExceptionConfig Maven / Gradle / Ivy
The newest version!
package com.github.rexsheng.springboot.faster.system.exception;
import com.github.rexsheng.springboot.faster.common.domain.Result;
import com.github.rexsheng.springboot.faster.common.domain.ResultCode;
import com.github.rexsheng.springboot.faster.system.modular.SpringModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Configuration
@ControllerAdvice
@ConditionalOnProperty(prefix = "app.module",name = "global-exception",havingValue = "true",matchIfMissing = true)
@SpringModule
public class ExceptionConfig {
private static final Logger logger= LoggerFactory.getLogger(ExceptionConfig.class);
@ExceptionHandler(Exception.class)
@ResponseBody
public Result onException(Exception e){
logger.error("onException",e);
if(e instanceof BindException exception){
String errorMsg=Stream.concat(exception.getGlobalErrors().stream().map(a->a.getDefaultMessage()),
exception.getFieldErrors().stream().map(a->a.getField()+":"+a.getDefaultMessage()))
.collect(Collectors.joining(";"));
return Result.error(ResultCode.BAD_REQUEST.getCode(),errorMsg);
}
if(e instanceof IllegalArgumentException exception){
return Result.error(ResultCode.BAD_REQUEST.getCode(),exception.getMessage());
}
return Result.error(e.getMessage());
}
@Configuration
@ControllerAdvice
@ConditionalOnProperty(prefix = "app.module",name = "global-exception",havingValue = "true",matchIfMissing = true)
@ConditionalOnClass(AccessDeniedException.class)
public static class AccessDeniedExceptionHandler{
@ExceptionHandler(AccessDeniedException.class)
@ResponseBody
public Result onException(AccessDeniedException e){
logger.error("onException",e);
return Result.error(ResultCode.ACCESS_DENIES.getCode(),e.getMessage());
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy