java自定义返回异常ResponsStatusExceptionResolver类
使用 ResponsStatusExceptionResolver类,注解 @ResponseStatus(value=HttpStatus.FORBIDDEN,reason="测试错误提示") 返回异常
1.此注解用在类上
写异常类:
package com.cc8w.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.FORBIDDEN,reason="测试错误提示") public class MyException extends Exception { /** * */ private static final long serialVersionUID = 1L; }
控制器抛出异常:
@RequestMapping("/getall") public @ResponseBody List<UserEntity> getall(@RequestParam(value = "pageNum",defaultValue="1") int pageNum,@RequestParam(value = "pageSize",defaultValue="1") int pageSize) throws MyException { PageHelper.startPage(pageNum, pageSize); List<UserEntity> userPojo = userService.getAll(); System.out.println(userPojo); if(pageNum==-1) { throw new MyException(); } return userPojo; }
2.此注解用在方法上:
@RequestMapping("/extest") public String exTest(@RequestParam(value = "i",defaultValue="1") int i) { if(i==-1) { return "redirect:error"; } return null; } /** * 自定义异常显示页面 * 使用ResponsStatusExceptionResolver,对应的注解 @ResponseStatus */ @RequestMapping("/error") @ResponseStatus(value=HttpStatus.FORBIDDEN,reason="测试错误提示func") public String exTest() { return "error"; }
访问:http://localhost:8080/java_security/home/index/extest?i=-1
会跳转: