首页 新闻 搜索 专区 学院

Spring validated 方法参数数据校验(基于注解)如何处理捕获后的异常?

0
[待解决问题]

我的代码如下:

package com.snsprj.controller;

import com.github.pagehelper.PageInfo;
import com.snsprj.common.ServerResponse;
import com.snsprj.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * Created by skh on 2017/6/27.
 */

@Controller
@RequestMapping("/product")
@Validated
public class ProductController {


    @Autowired
    private IProductService iProductService;


    @RequestMapping("list")
    @ResponseBody
    public ServerResponse<PageInfo> getProductList(@Min(0) Integer category_id,
                                                        @NotNull Integer page_num){

        // TODO 若 categoryId=0 则显示所有商品

        Byte status = 1;

        PageInfo page = iProductService.getProductByCategoryId(category_id,status,page_num,1);


        return ServerResponse.createBySuccess(page);
    }

}

我的问题是怎么设置提示信息呢?比如提示:category_id必须为大于等于0的整数。

我配置了spring全局异常捕获,代码如下:

package com.snsprj.common.exception;

import com.snsprj.common.ServerResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;

/**
 * Created by skh on 2017/6/29.
 */
public class DefaultExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {

        ModelAndView mv = new ModelAndView();

        // handle ConstraintViolationException
        if(ex instanceof ConstraintViolationException){

            // set status code
            response.setStatus(HttpStatus.OK.value());

            // set content type
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);

            // set character encoding
            response.setCharacterEncoding("UTF-8");

            response.setHeader("Cache-Control", "no-cache, must-revalidate");

            try {
                // TODO get detail error message

                response.getWriter().write("{\"success\":false,\"msg\":\" invalid parameter!\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }




        return mv;
    }
}
景岳的主页 景岳 | 初学一级 | 园豆:16
提问于:2017-06-29 14:08
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册