package com.ihooyah.common.handler;

import com.ihooyah.common.exception.BaseException;
import com.ihooyah.common.exception.UserTokenException;
import com.ihooyah.common.msg.RespEnum;
import com.ihooyah.common.msg.RespInfo;
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 RespInfo validateErrorHandler(HttpServletResponse response, BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors() && bindingResult.getFieldError() != null) {
            return new RespInfo(RespEnum.ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }else{
            return new RespInfo(RespEnum.ERROR.getCode(),"Form validation error");
        }
    }


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

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

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



}
