package com.friday.custody.common.filter;

import com.friday.custody.exception.RRException;
import com.friday.custody.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 统一异常处理方法
 */
@Slf4j
@RestControllerAdvice
public class SpringMvcExceptionHandler {
    @ExceptionHandler
    public Object exceptionHandler(Exception e) {
        log.error("SpringMvcExceptionHandler:",e);
        if (e instanceof RRException) {
            RRException rrException= (RRException) e;
            return R.error(rrException.getCode(),  rrException.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            //jsr 303 抛出的异常
            HashMap<String, String> errorMap = new HashMap<>();
            ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors().forEach(fieldError -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
            return R.error(400, "参数错误").put("data",errorMap);
        } else {
            return R.error(500, "操作失败").put("data","未知异常，请联系系统管理员！");
        }
    }
}
