package com.ihooyah.common.handler;

import com.ihooyah.common.exception.BaseException;
import com.ihooyah.common.exception.UserTokenException;
import com.ihooyah.common.msg.ObjectRespInfo;
import com.ihooyah.common.msg.RespEnum;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice("com.ihooyah")
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public ObjectRespInfo validateErrorHandler(HttpServletResponse response, BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors() && bindingResult.getFieldError() != null) {
            return new ObjectRespInfo(RespEnum.ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }else{
            return new ObjectRespInfo(RespEnum.ERROR.getCode(),"Form validation error");
        }
    }


    @ExceptionHandler(UserTokenException.class)
    public ObjectRespInfo userTokenExceptionHandler(HttpServletResponse response, UserTokenException ex) {
        return new ObjectRespInfo(ex.getStatus(),ex.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public ObjectRespInfo baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        return new ObjectRespInfo(RespEnum.ERROR.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ObjectRespInfo otherExceptionHandler(HttpServletResponse response, Exception ex) {
        return new ObjectRespInfo(RespEnum.ERROR.getCode(), ex.getMessage());
    }



}
