package cn.com.qmth.examcloud.tool.config;

import cn.com.qmth.examcloud.tool.utils.StatusException;
import cn.com.qmth.examcloud.tool.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ResponseBody
@ControllerAdvice
public class ControllerAdviceHandler {

    private final static Logger log = LoggerFactory.getLogger(ControllerAdviceHandler.class);

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Result<Object>> handle(Exception e) {
        log.error(e.getMessage(), e);

        if (e instanceof StatusException) {
            return new ResponseEntity<>(new Result<>(((StatusException) e).getCode(), e.getMessage()),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        } else if (e instanceof HttpMessageConversionException) {
            return new ResponseEntity<>(
                    new Result<>(String.valueOf(HttpStatus.BAD_REQUEST.value()), "参数值类型转换错误！"),
                    HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity<>(
                new Result<>(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

}