package com.jiayue.ipfcst.common.core.web;

import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

/**
 * 全局异常处理
 *
 * @author zzy
 * @version 1.0
 * @since 2019/11/25 14:35
 */
@Slf4j
@ControllerAdvice(
        annotations = {RestController.class, Controller.class}
)
public class GlobalExceptionHandler {
    private static final String ERROR_MSG_TPL = "ip: %s, path: %s, message: %s";

    /**
     * 处理业务异常
     *
     * @param request
     * @param exception
     * @return com.jiayue.ipfcst.common.core.web.vo.ResponseVO
     * @author L.ym
     * @date 2020/1/14
     **/
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({BusinessException.class})
    public ResponseVO handleExceptionInternal(HttpServletRequest request, BusinessException exception) {
        log.error(String.format(ERROR_MSG_TPL, request.getRemoteAddr(), request.getRequestURI() + Optional.ofNullable(request.getQueryString()).orElse(""), exception.getMessage()), exception);
        return ResponseVO.fail(exception);
    }

    /**
     * 处理全局异常
     *
     * @param request
     * @param throwable
     * @return com.jiayue.ipfcst.common.core.web.vo.ResponseVO
     * @author L.ym
     * @date 2020/1/14
     **/
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({Throwable.class})
    public ResponseVO defaultErrorHandler(HttpServletRequest request, Throwable throwable) {
        log.error(String.format(ERROR_MSG_TPL, request.getRemoteAddr(), request.getRequestURI() + Optional.ofNullable(request.getQueryString()).orElse(""), throwable.getMessage()), throwable);
        return ResponseVO.error(throwable);
    }
}