美文网首页
@ControllerAdvice

@ControllerAdvice

作者: 某某程序员_ | 来源:发表于2019-10-29 11:58 被阅读0次

@ExceptionHandler 异常统一处理

处理web请求中的异常

@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class WebControllerAdvice {
    private Logger logger = LoggerFactory.getLogger(WebControllerAdvice.class);
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Result handleException(Throwable throwable) throws IOException {
        Result res = Result.error("内部异常,请稍后再试");
        if(throwable instanceof Exception){
            res.setDesc(throwable.getMessage());
        }
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        logger.error("invoke fail: url={}", getPath(request), throwable);
        return res;
    }

}

@RestController
public class HelthCheckController {

    @RequestMapping(value = "version/status", method = RequestMethod.GET)
    public String health(int i){
        return "OK";
    }

}

请求:
http://localhost:8091/version/status?i=xxx

返回:
{"code":-1,"desc":"Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "xxx""}

异常情况优雅的返回自定义数据。

注释掉WebControllerAdvice 类,
返回结果:


image.png

@ModelAttribute 请求过程中对参数进行设置

定义全局参数:

@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class WebControllerAdvice {
    @ModelAttribute("param")
    public String m(){
        return "10001";
    }
}

使用ModelAttribute定义的全局参数
@RestController
public class HelthCheckController {
    @RequestMapping(value = "version/status", method = RequestMethod.GET)
    public String health(@ModelAttribute("param") String param){
        return param;
    }
}

请求:
http://localhost:8091/version/status
返回结果:"10001"

@InitBinder,当多个不同实体的多个参数名称相同时,使用前缀进行区分

设置参数前缀

    @InitBinder("user")
    public void InitBinder(WebDataBinder webDataBinder){
        webDataBinder.setFieldDefaultPrefix("user.");
    }
  
    @RequestMapping(value = "version/status", method = RequestMethod.POST)
    public String health(@ModelAttribute("param") String param, @ModelAttribute("user")User user){
        return JSONObject.toJSONString(user);
    }

public class User implements Serializable{

    private final static Long serialVersionUID = -1L;

    private String a;
    private String b;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }
}

请求:POST http://localhost:8091/version/status?user.a=1&user.b=2
结果:{"a":"1","b":"2"}

相关文章

网友评论

      本文标题:@ControllerAdvice

      本文链接:https://www.haomeiwen.com/subject/nafevctx.html