package cn.reghao.oss.console.config.web;

import cn.reghao.jutil.jdk.exception.ExceptionUtil;
import cn.reghao.jutil.jdk.result.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 全局异常处理类，处理 controller 抛出的异常
 *
 * @author reghao
 * @date 2019/03/21 10:25:49
 */
@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {
    /**
     * 处理所有 controller 上抛出的异常
     *
     * @date 2019-09-28 上午11:01
     */
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResponseEntity<String> error(Exception e, HttpServletRequest request) {
        ExceptionUtil.errorMsg(e);
        String stackTrace = ExceptionUtil.stackTrace(e);
        log.error("请求错误 -> {}", stackTrace);
        String msg = e.getMessage();
        if (msg == null) {
            msg = e.toString();
        }
        return setResponse(msg);
    }

    /**
     * 表单提交验证异常
     *
     * @param
     * @return
     * @date 2021-05-18 下午3:36
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<String> bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
        return setResponse(msg);
    }

    private ResponseEntity<String> setResponse(String body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>(WebResult.errorWithMsg(body), headers, HttpStatus.OK);
    }
}
