package com.reptileclient.jlifeapp.result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created with IntelliJ IDEA.
 * User: ABC
 * Date: 2018/5/23
 * Time: 3:25 PM
 * @author fuxubing
 */
@RestControllerAdvice
public class ResponseInfoHandler {
    private static final Logger logger = LoggerFactory.getLogger(ResponseInfoHandler.class);

    @ExceptionHandler(value = ResponseInfoException.class)
    public ResultBody responseInfoExceptionHandler(ResponseInfoException exception) {
        ResponseInfoInterface responseInfoInterface = exception.getResponseInfoInterface();
        ResultBody resultBody = new ResultBody(responseInfoInterface);
        return resultBody;
    }

    @ExceptionHandler(value = MyRuntimeException.class)
    public ResultBody checkRuntimeExceptionHandler(MyRuntimeException exception) {
        ResponseInfoInterface responseInfoInterface = exception.getResponseInfoInterface();
        ResultBody resultBody = new ResultBody(responseInfoInterface);
        return resultBody;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBody invalidInput(MethodArgumentNotValidException ex) {
        logger.error(ex.getMessage());
        ResultBody result = new ResultBody(ResponseInfoEnum.ERROR);
        result.setMessage(ex.getBindingResult().getFieldError().getDefaultMessage());
        return result;
    }

}
