package org.matrix.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * GlobalExceptionHandler. 全局异常处理类
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2022/1/19 at 12:54 PM
 * Suffering is the most powerful teacher of life.
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 报错信息都会通过这个方法处理并通过统一的返回方式进行返回
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> errorMessage(Exception e) {
        log.error("[其他异常] {}", e.toString());
        e.printStackTrace();
        return ResponseEntity.status(500).body("服务器异常" + e.getMessage());
    }

    /**
     * 业务错误
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(GlobalException.class)
    public ResponseEntity<String> errorMessage(GlobalException e) {
        log.warn("[自定义异常]" + e.toString());
        e.printStackTrace();
        return ResponseEntity.status(400).body(e.getMessage());
    }

}
