package com.brframework.commonweb.core;

import com.brframework.commonweb.exception.HandleException;
import com.brframework.commonweb.json.JSONResult;
import com.brframework.commonweb.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @Author xu
 * @Date 2017/12/28 0028 上午 11:43
 * Restful api 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class RestExceptionHandler {

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public JSONResult allExceptionHandler(Throwable e) {

        if(e instanceof MethodArgumentNotValidException){
            //验证参数输入错误
            return JSONResult.error(new HandleException(
                    ((MethodArgumentNotValidException)e).getBindingResult().getFieldError().getDefaultMessage())
            );
        } else if(e instanceof BindException){
            return JSONResult.error(new HandleException(
                    ((BindException)e).getBindingResult().getFieldError().getDefaultMessage())
            );
        } else if( e instanceof HandleException){
            return JSONResult.error((HandleException) e);
        }

        //系统出现意外情况的错误
        printError(e);

        return JSONResult.error(e);
    }

    /**
     * 系统出现意外情况的错误时整理打印错误信息
     * @param e
     */
    private void printError(Throwable e){
        log.error("请求意外终止，异常产生URI:{}，请留意以下堆栈信息", ServletUtils.request().getRequestURI(), e);

    }



}
