package com.nova.sankuai.infra.exception; import com.nova.sankuai.infra.constants.ResultCode; import com.nova.sankuai.infra.config.CommonException; import com.nova.sankuai.infra.utils.ResultJson; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.stereotype.Component; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; /** * @author weikangdi */ @Slf4j @RestControllerAdvice @Component public class ExceptionHandlerAdvice { private static final Logger logger = LoggerFactory.getLogger("exceptionLogger"); @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity handleMethodArguemntNotValidException(MethodArgumentNotValidException e) { e.printStackTrace(); logger.error("参数或者语法不对", e); return ResponseEntity.status(HttpStatus.OK).body(ResultJson.failure(ResultCode.BAD_REQUEST, e.getBindingResult().getFieldError().getDefaultMessage())); } /** * 权限不足 */ @ExceptionHandler(InsufficientAuthenticationException.class) public ResponseEntity handleInsufficientAuthenticationException(InsufficientAuthenticationException e, HttpServletRequest request) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未登录或该账号没有权限"); } @ExceptionHandler(CommonException.class) public ResponseEntity handleCommonException(CommonException e, HttpServletRequest request) { return ResponseEntity.status(HttpStatus.OK).body(ResultJson.failure(ResultCode.SERVER_ERROR, e.getMessage())); } @ExceptionHandler(RuntimeException.class) public ResponseEntity handleRuntimeException(RuntimeException e, HttpServletRequest request) { e.printStackTrace(); logger.error("系统内部错误", e); return ResponseEntity.status(HttpStatus.OK).body(ResultJson.failure(ResultCode.SERVER_ERROR, e.getMessage())); } }