-
错误html页面(会根据错误自动跳转到页面)
-
如果报错运行时异常会跳转到500.html
-
使用Restlet Client来测试
-
自定义UserNotExistException类
package com.imooc.exception;
public class UserNotExistException extends RuntimeException {
/**
* 序列号
*/
private static final long serialVersionUID = 1L;
private String id;
public UserNotExistException(String id) {
super("user not exist");
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
- 加载错误类的注解类
package com.imooc.web.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.imooc.exception.UserNotExistException;
/**
* 加载自定义错误
* @author caijiajun
* @date 2018年9月11日
*/
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(UserNotExistException.class)//加载自定义错误类
@ResponseBody//返回json格式
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//表明注解的类型
public Map<String, Object> handlerUserNotExistException(UserNotExistException ex) {
Map<String, Object> result = new HashMap<>();
result.put("id", ex.getId());
result.put("message", ex.getMessage());
return result;
}
}
- 模拟错误发生
@GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable(name = "id") String id) {
throw new UserNotExistException(id);
// System.out.println("进入getInfo服务");
// User user = new User();
// user.setUsername("tom");
// return user;
}
- 用Restlet Client 测试
- @JsonView的用法
@JsonView返回实体类中指定字段属性
控制controller
@GetMapping
//指定参数名称@RequestParam(value = "usename", required = false ,defaultValue = "tom")
@JsonView(User.UserSimpleView.class)
@ApiOperation(value = "用户查询服务")
public List<User> query(UserQueryCondition condition,@PageableDefault(page = 2 ,size =17, sort = "asc") Pageable pageable) {
//反射的一个tostring工具
System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));
System.out.println(pageable.getPageSize());
System.out.println(pageable.getPageNumber());
System.out.println(pageable.getSort());
List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
9.用Restlet Client 测试
注意:子接口如果继承父接口,那么返回的字段也包括父接口上添加的字段